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