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

Javascript Fetch upload files to 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" />

the https://tongsampah.herokuapp.com is just a dummy api server that I use to test. It will returns the request details as a response

您可能需要确保字段名称正确(例如 {target}_cand -- 我不知道目标值是什么)