Ajax使用formdata异步上传文件,报错the request was rejected because no multipart boundary was found
Posted 简一118
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ajax使用formdata异步上传文件,报错the request was rejected because no multipart boundary was found相关的知识,希望对你有一定的参考价值。
基于jQuery的Ajaxs使用FormData上传文件要注意两个参数的设定
processData设为false
把processData设为false,让jquery不要对formData做处理,如果processData不设置为false,jquery会把formData转换为字符串。
contentType设为false
http发送multipart/form-data请求报文示例
POST /api/feed/ HTTP/1.1
Accept-Encoding: gzip
Content-Length: 225873
Content-Type: multipart/form-data; boundary=OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp
Host: www.myhost.com
Connection: Keep-Alive
--OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp
Content-Disposition: form-data; name="lng"
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
116.361545
--OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp
Content-Disposition: form-data; name="lat"
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
39.979006
--OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp
Content-Disposition: form-data; name="images"; filename="/storage/wbavrx.jpg"
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
这里是图片的二进制数据
--OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp--
注意Content-Type: multipart/form-data; boundary=OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp
,参数boundary为请求参数之间的界限标识。
如果jquery请求设置了contentType,那么就会覆盖了formData的content-type,导致服务器在分隔参数和文件内容时是找不到boundary,报no multipart boundary was found
错误
默认情况下jquery会把contentType设置为application/x-www-form-urlencoded。要jquery不设置contentType,则需要把contentType设置为false。
var formData = new FormData($("#uploadform")[0]); $.ajax({ url: actionUrl, type: ‘POST‘, data: formData, async: false, cache: false, contentType: false, processData: false, ... });
以上是关于Ajax使用formdata异步上传文件,报错the request was rejected because no multipart boundary was found的主要内容,如果未能解决你的问题,请参考以下文章
(H5)FormData+AJAX+SpringMVC跨域异步上传文件
.Net之使用Jquery Ajax通过FormData对象异步提交图片文件到服务端保存并返回保存的图片路径