基于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, ... });
原文地址:https://www.cnblogs.com/zhangym118/p/9029269.html
时间: 2024-10-09 02:48:22