基於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, ... });