Ajax使用formdata異步上傳文件,報錯the request was rejected because no multipart boundary was found

原文:https://www.itread01.com/content/1526126668.htmlhtml

 

基於jQuery的Ajaxs使用FormData上傳文件要註意兩個參數的設定jquery

processData設為falseajax

把processData設為false,讓jquery不要對formData作處理,若是processData不設置為false,jquery會把formData轉換為字符串。api

contentType設為falseapp

http發送multipart/form-data請求報文示例async

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為請求參數之間的界限標識。post

若是jquery請求設置了contentType,那麼就會覆蓋了formData的content-type,導致服務器在分隔參數和文件內容時是找不到boundary,報no multipart boundary was found錯誤url

默認情況下jquery會把contentType設置為application/x-www-form-urlencoded。要jquery不設置contentType,則須要把contentType設置為false。spa

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