formData上传文件无需设置Content-Type

用FormData在提交数据时候,会自动设置 Content-Type。

无论提交普通字段,还是上传文件,都无需自行设置 Content-Type。

尤其在上传文件时候,自行设置 Content-Type: multipart/form-data,反而会导致上传失败。

因为浏览器自行添加的 Content-Type,除了multipart/form-data,还会带上个boundary,

自行添加,会导致boundary丢失,服务器就不知道如何分割字段,导致上传失败。

下面是xhr,fetch,axios,jquery上传文件方法汇总:

复制代码
const fd = new FormData()
let imageBlob = params.file;
fd.append('file', imageBlob)

//xhr上传文件
const xhr = new XMLHttpRequest()
xhr.open('POST', params.url, true)
//xhr.setRequestHeader("Content-type","multipart/form-data")
xhr.send(fd)
xhr.onreadystatechange = () => {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log('uploadFile xhr res: ', xhr)
        let res = JSON.parse(xhr.responseText);
        params.success(res)
    }
    else{
        console.log('uploadFile xhr error: ', xhr)
        params.fail(xhr)
    }
}

//fetch上传文件
fetch('xxx/upload', {
    method: 'POST',
    body: fd,
    headers: {
      //'Content-Type': 'multipart/form-data'
    }
}).then(res => {
    if(res.ok) {
        return res.json();
    } else {
        console.log('error')
    }
}).then(res => {
    console.log('res is',res);
})

//axios上传文件
async function uploadFile(event) {
    const file = event.target.files[0]
    let formData = new FormData()
    formData.append('files', file)
    const res = await axios({
      url: '/api/files/upload',
      method: 'POST',
      transformRequest: [function(data, headers) {
        // axios会自动设置post的请求头为application/x-www-form-urlencoded
        // 所以必须清除post请求默认的Content-Type
        delete headers.post['Content-Type']
        return data
      }],
      data: formData
    })
}

//jqery上传文件
async function uploadFile(){
    return $.ajax({
        method: 'POST',
        url: 'xxx/upload',
        data: fd,
        // 不修改 Content-Type 属性,使用 FormData 默认的 Content-Type 值
        contentType: false,
        // 不对 FormData 中的数据进行 url 编码,而是将 FormData 数据原样发送到服务器
        // jQuery会将data对象转换为字符串来发送HTTP请求,默认情况下会用 application/x-www-form-urlencoded编码来进行转换。 
        // 设置contentType: false后该转换会失败,因此设置processData: false来禁止该转换过程。
        // data是已经用FormData编码好的数据,不需要jQuery进行字符串转换
        processData: false,
        success: function(res) {
           console.log(res)
        }
   })
}
复制代码

 

参考: https://blog.csdn.net/C_L99/article/details/124437743

posted @   全玉  阅读(1192)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示