码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2018-05-12 18:28:34      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:query   nec   rip   accept   报错   二进制   div   because   文件内容   

基于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

标签:query   nec   rip   accept   报错   二进制   div   because   文件内容   

原文地址:https://www.cnblogs.com/zhangym118/p/9029269.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!