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

使用jQuery和Ajax发送Excel文件时的contentType配置问题求助

问题分析与解决方案

你的代码存在几个核心错误,导致文件上传请求格式不符合API要求,以下是修正方案:

核心错误点

  1. 错误地将FormData包装成数组和对象,破坏了文件上传所需的multipart/form-data结构
  2. AJAX配置参数误用:dataType被错误用作发送数据的字段,contentType拼写错误且手动设置方式不正确

修正后的代码

前端文件处理部分

let fileName;

$("#commodityAH_massEdit").on("click", function () {
    $('#loadHolidayModal').modal('show');
});

$('#myFile').change(function(e){
    fileName = $("#myFile").prop('files')[0];
    console.log("the file selected is", fileName);
})

$("#btn-massEdit").on("click", function () {
    if (!fileName) {
        alert('请先选择文件');
        return;
    }
    // 每次点击创建新的FormData实例,避免重复添加文件
    const form = new FormData();
    form.append('filename', fileName, fileName.name);
    
    // 直接传入FormData,无需额外包装
    $.fn.updateSupplier(form)
        .then(res => {
            console.log("keys length", Object.keys(res).length)
            if (res != undefined && Object.keys(res).length > 0) {
                selectCommodities = [];
                $('#massEditModal').modal('hide');
                $('#message-massedit').text('');
                $("#successMassEdit").find('.message').html('Supplier updated successfully!');
                $('#successMassEdit').modal('show');
                Self.initTable();
            } else {
                selectCommodities = [];
                $('#massEditModal').modal('hide');
                $('#message-massedit').text('');
                $("#messageMassFail").find('.message').html('Supplier Failed to update!');
                $('#messageMassFail').modal('show');
                console.error(res);
            }
        })
        .catch(err => {
            console.error('update Supplier err', err);
        })
});

API调用部分

$.fn.updateSupplier = function (formData) {
    console.log("the post data being sent is", formData)
    return new Promise((resolve, reject) => {
        $.ajax({
            type: "POST",
            url: "https://admin-business.azurewebsites.net/api/uploadBusinessSupplies",
            data: formData, // 发送FormData实例
            processData: false, // 禁止jQuery自动处理FormData
            contentType: false, // 让jQuery自动生成带边界符的multipart/form-data请求头
            headers: {
                jwt: $.cookie("jwt")
            }
        })
        .done(function (res) {
            resolve(res);
        })
        .fail(function (err) {
            reject(err);
        });
    })
}

关键修正说明

  1. FormData使用规范:文件上传必须直接传递FormData实例,不能将其包装成数组或JSON对象,否则请求体格式会完全偏离API要求的multipart/form-data类型。
  2. AJAX参数修正:
    • dataType是用来指定预期的响应数据类型(如json),发送数据应使用data字段。
    • contentType设为false是关键:手动设置multipart/form-data会缺失必要的边界标识符,jQuery会自动为FormData生成正确的请求头。
    • processData必须设为false,防止jQuery将FormData转换为字符串格式。
  3. 避免重复上传:每次点击按钮创建新的FormData实例,防止多次点击导致同一个文件被重复添加到请求中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:30:47