Javascript获取上传文件到Python Flask-restful



我是新的python和javascript,我已经给了一个任务来创建一个表单,我需要上传一个文件。我需要击中后端(flask restful API)。我被告知这是我需要发送请求的方式

requests.post(f"{server}/v1/cand", files={f"{target}_cand": cand_data})

我尝试使用fetch api从javascript命中,我得到201创建的响应,但后端接收的文件是空的。我不知道我的请求格式是否正确,

var data = new FormData()
data.append('files', files[0])
data.append('name', fileName)
console.log(data.get('files'))
fetch("http://localhost:5001/v1/cand",{
method:"POST",
body: {files:files[0]},
})
.then(function(response){
return response.json()
})
.then(function(data){
console.log('success')
console.log(data)
})

这是后端接收它的方式

def post(self):
cand= []
for f in request.files:
//do something

请帮我解决这个问题。

对不起,我真不敢相信我错过了显而易见的东西。在请求中不发送FormData实例。你可以这样做:

document.querySelector('#fileUpload').addEventListener('change', event => {
let files = event.target.files
let fileName = files[0].name

// your code start here
var data = new FormData()
data.append('files', files[0]) // maybe it should be '{target}_cand'
data.append('name', fileName)
console.log(data.get('files'))
// let url = "http://localhost:5001/v1/cand"
let url = "https://tongsampah.herokuapp.com"
fetch(url,{
method:"POST",
// body: {files:files[0]}, // wrong
body: data,
})
.then(function(response){
return response.json()
})
// .then(function(data){ // use different name to avoid confusion
.then(function(res){
console.log('success')
console.log(res)
})
})
<input type="file" id="fileUpload" />

https://tongsampah.herokuapp.com只是我用来测试的虚拟api服务器。它将作为响应

返回请求详细信息。

您可能需要确保字段名是正确的(例如:{target}_cand——我不知道目标值是多少)

最新更新