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
标签:
JavaScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具