ajax上傳檔案的請求

陳鳳娟發表於2017-12-27

1、data是FormData

傳送的data必須是FormData型別

2、注意processData

把processData設為false,讓jquery不要對formData做處理,如果processData不設定為false,jquery會把formData轉換為字串。

3、contentType

檢視檔案上傳的請求頭裡Content-Type: multipart/form-data; boundary=OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp ,引數boundary為請求引數之間的界限標識。
這裡的Content-Type不是你設定的,而是FormData的content-type。

如果jquery請求設定了contentType,那麼就會覆蓋了formData的content-type,導致伺服器在分隔引數和檔案內容時是找不到boundary,報no multipart boundary was found錯誤

預設情況下jquery會把contentType設定為application/x-www-form-urlencoded。要jquery不設定contentType,則需要把contentType設定為false。

也就是說contentType:false,防止contentType覆蓋掉formData的content-type。

4、example

var data=new FormData();
$.each(files,function (i, file) {
    data.append("file",file);
});
$.ajax({url:``,
        type:`post`,
        contentType:false,
        processData:false,
        data:data,
        success:function () {
            console.log("111");
        }
});

相關文章