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

使用fetch-api从JS前端上传Excel到Flask后端报错求助

Flask + Fetch API Excel文件上传报错排查与修复

问题概述

使用Fetch API从前端上传Excel文件到Flask后端时出现报错,以下是排查出的核心问题及修复方案:


核心错误点及修复

1. 表单默认提交行为干扰Fetch请求

前端按钮位于<form>标签内,点击时会触发表单默认提交,导致页面刷新,直接中断Fetch请求。
修复: 将按钮类型改为button,避免触发表单默认提交:

<button type="button" onclick="uploadDocument()"> Upload </button>

2. FormData键名与后端接收名不匹配

前端FormData中文件的键是'file',但后端检查的是'excel_file',导致后端无法识别上传的文件。
修复: 统一两端键名,修改前端FormData部分:

formData.append('excel_file', fileInput.files[0]);

3. Flask配置引用错误

后端代码中使用app.CONFIG['UPLOAD_FOLDER'](大写CONFIG),但Flask的配置属性是小写的app.config,会导致属性不存在报错。
修复: 改为小写的app.config。

4. 文件路径拼接错误

patha是元组格式,直接传入os.path.join会导致路径拼接失败,os.path.join需要接收多个独立参数。同时要确保上传文件夹存在,否则保存文件时会报错。
修复:

upload_dir = os.path.join(os.path.abspath(dirname1), app.config['UPLOAD_FOLDER'])
# 确保上传目录存在
if not os.path.exists(upload_dir):
    os.makedirs(upload_dir)
file_path = os.path.join(upload_dir, filename)

5. 后端路由无返回值

upload_excel函数处理完文件后没有返回任何响应,Flask会默认返回500内部错误,前端无法获取正确结果。
修复: 添加成功响应:

return jsonify({"message": "文件上传成功"}), 200

修改后的完整代码

前端HTML(docUpload.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h2>Upload a Document</h2>
    <form method="POST">
        <input type="file" id="fileInput" accept=".xlsx, .xls">
        <button type="button" onclick="uploadDocument()"> Upload </button>
    </form>
    <p id="status"></p>
    <script>
        async function uploadDocument() {
            const fileInput = document.getElementById('fileInput');
            const status = document.getElementById('status');
            
            if (fileInput.files.length === 0) {
                status.innerText = "Please select a file first.";
                return;
            }

            const formData = new FormData();
            formData.append('excel_file', fileInput.files[0]);

            try {
                const response = await fetch('http://127.0.0.1:6969/upload', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                console.log(result)
                status.innerText = result.message || result.error;
            } catch (error) {
                status.innerText = "An error occurred during upload.";
                console.error(error);
            }
        }
    </script>
</body>
</html>

后端Python代码

from flask import Flask, render_template, jsonify, request
from flask_cors import CORS
from waitress import serve
import os
from werkzeug.utils import secure_filename

app = Flask(__name__)
CORS(app)
app.config['UPLOAD_FOLDER'] = 'upload'

@app.route('/')
def index():
    return render_template("upload.html")

@app.route('/docUpload')
def addData():
     return render_template("docUpload.html")

@app.route('/upload', methods = ['POST'])  
def upload_excel():  
    if 'excel_file' not in request.files:
        return jsonify({"error": "no file uploaded"}), 400
    
    file = request.files['excel_file']

    if file.filename == '':
        return jsonify({"error": "No selected file"}),400
    
    filename = secure_filename(file.filename)
    dirname1 = os.path.dirname(__file__)
    upload_dir = os.path.join(os.path.abspath(dirname1), app.config['UPLOAD_FOLDER'])
    if not os.path.exists(upload_dir):
        os.makedirs(upload_dir)
    file_path = os.path.join(upload_dir, filename)
    file.save(file_path)
    
    return jsonify({"message": "文件上传成功"}), 200

if __name__ == "__main__":
    serve(app, host='0.0.0.0', port=6969)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.02 06:54:53