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

Vue通过Fetch上传文件至Flask API遇CORS及文件读取异常

问题原因及解决办法

1. 前端手动设置Content-Type导致表单解析失败

当使用FormData作为请求体时,浏览器会自动生成包含boundary的Content-Type头(比如multipart/form-data; boundary=----WebKitFormBoundaryXXXX),手动设置固定的Content-Type: multipart/form-data会丢失boundary参数,导致后端无法正确解析表单数据,这是触发BadRequestKeyError的直接原因。

前端修复代码:

移除手动设置的Content-Type头,让浏览器自动处理,同时修正text()方法的异步处理:

let file = new FormData();
let imageFile = document.getElementById("select-image").files[0];
file.append("file", imageFile, "file");

fetch('http://localhost:5000/image-file',
  {
    method: 'PUT',
    headers: {
      'Authorization': token
    },
    body: file
  })
  .then(async http => {
    let response = await http.text();
    if (http.ok) {
      console.log("created")
    } else {
      throw new Error(response);
    }
  })
  .catch(error => {
    console.log(error);
  })

2. 后端文件读取逻辑与异常处理缺失

后端需要正确使用request.files获取上传文件,同时要处理文件不存在的情况,避免未捕获的异常导致500响应,进而引发CORS头缺失问题。

后端修复代码:

from flask import request

@app.route("/image-file", methods=["PUT"])
@user_only
def new_image_file(artist_name):
    # 检查请求中是否包含文件
    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 "complete"

3. CORS响应头在错误场景下缺失

当后端抛出未捕获的异常时,Flask默认错误处理返回的500响应不会自动添加CORS头,导致前端看到CORS错误。需要确保错误响应也包含CORS头。

修复方案:

添加全局错误处理函数,给错误响应注入CORS头:

from flask import jsonify

@app.errorhandler(400)
def bad_request(error):
    response = jsonify({'message': str(error)})
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response, 400

@app.errorhandler(500)
def internal_error(error):
    response = jsonify({'message': 'Internal server error'})
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response, 500

也可以在全局CORS配置中启用凭证支持,确保错误响应也能带上CORS头:

CORS(app, supports_credentials=True)

问题链总结

  1. 前端手动设置Content-Type丢失boundary → 后端无法解析FormData → 抛出BadRequestKeyError
  2. 后端未捕获该异常,返回500响应且未添加CORS头 → 前端先触发CORS错误,随后显示500内部错误

按上述步骤修复后,即可正常完成图片上传请求。

内容的提问来源于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:33:33