Ajax使用formdata异步上传文件,报错the request was rejected because no multipart boundary was found

基于jQuery的Ajaxs使用FormData上传文件要注意两个参数的设定javascript

processData设为falsejava

把processData设为false,让jquery不要对formData作处理,若是processData不设置为false,jquery会把formData转换为字符串。jquery

contentType设为falseajax

http发送multipart/form-data请求报文示例api

 

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错误app

默认状况下jquery会把contentType设置为application/x-www-form-urlencoded。要jquery不设置contentType,则须要把contentType设置为false。async

var formData = new FormData($("#uploadform")[0]);
$.ajax({
    url: actionUrl,
    type: 'POST',
    data: formData,
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    ...
});
相关文章
相关标签/搜索