You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Fetch API上传文件至Flask API时request.files为空的问题

问题:Fetch API上传文件到Flask时request.files为空

我尝试通过JavaScript的Fetch API向Flask API上传文件,请求构造代码如下:

let file = new FormData();
let imageFile = document.getElementById("select-image").files[0];
file.append("file", imageFile);
fetch('http://localhost:5000/image-file',
  {
    method: 'PUT',
    headers: {
      'Content-Type': 'multipart/form-data',
      'Authorization': token
    },
    body: file
  })
  .then(async http => {
    let response = http.text();
    if (http.ok) {
      console.log("created")
      postImageData(text);
    }
    else {
      return response.then(response => {throw new Error(response);})
    }
  })
  .catch(error => {
    console.log(error);
  })

但在Flask中调用request.files时得到空对象,request.files["file"]会报错。查看请求负载如下:

------WebKitFormBoundaryG7nrDvgPSk3FSRUs
Content-Disposition: form-data; name="file"; filename="2480_books2.jpg"
Content-Type: image/jpeg


------WebKitFormBoundaryG7nrDvgPSk3FSRUs--

文件上传元素代码:

<input id="select-image" name="image" type="file"/><br/>

请问当前请求能否正常获取文件,还是请求本身存在问题?


解决方案

你的请求存在问题,核心原因是手动设置的请求头导致Flask无法正确解析表单数据。

关键错误点:

当使用FormData作为Fetch的请求体时,浏览器会自动生成包含boundary(分隔符)的Content-Type头,格式类似multipart/form-data; boundary=----WebKitFormBoundaryxxxx。而你手动设置的Content-Type: multipart/form-data缺少boundary信息,Flask无法识别表单字段的分隔规则,因此解析不到request.files中的内容。

修复步骤:

  1. 移除手动设置的Content-Type头,让浏览器自动处理:
fetch('http://localhost:5000/image-file',
  {
    method: 'PUT',
    headers: {
      // 删掉这一行:'Content-Type': 'multipart/form-data',
      'Authorization': token
    },
    body: file
  })
  1. 修复回调中的变量错误:你定义了let response = http.text(),但后续调用postImageData(text)时text未定义,且http.text()是异步操作需要加await:
.then(async http => {
  let response = await http.text();
  if (http.ok) {
    console.log("created")
    postImageData(response);
  }
  else {
    throw new Error(response);
  }
})
  1. Flask端确认路由配置:确保路由接受PUT方法,逻辑正确:
from flask import Flask, request

app = Flask(__name__)

@app.route('/image-file', methods=['PUT'])
def upload_file():
    if 'file' not in request.files:
        return 'No file part', 400
    file = request.files['file']
    if file.filename == '':
        return 'No selected file', 400
    # 这里添加文件处理逻辑,比如保存到服务器
    # file.save(f'uploads/{file.filename}')
    return 'File uploaded successfully', 200

if __name__ == '__main__':
    app.run(debug=True)

完成以上修改后,Flask就能正常通过request.files["file"]获取到上传的文件了。

内容的提问来源于stack exchange,提问作者jban28

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 20:52:31