FormData對象,是可以使用一系列的鍵值對來模擬一個完整的表單,然后使用XMLHttpRequest發送這個"表單"。
在 Mozilla Developer 網站 使用FormData對象 有詳盡的FormData對象使用說明。
但上傳文件部分只有底層的XMLHttpRequest對象發送上傳請求,那么怎么通過jQuery的Ajax上傳呢?
本文將介紹通過jQuery使用FormData對象上傳文件。
HTML代碼
<
form
id
="uploadForm"
enctype
="multipart/form-data"
>
< input id ="file" type ="file" name ="file" />
< button id ="upload" type ="button" >upload </ button >
</ form >
< input id ="file" type ="file" name ="file" />
< button id ="upload" type ="button" >upload </ button >
</ form >
javascript代碼
$.ajax({
url: '/upload',
type: 'POST',
cache: false,
data: new FormData($('#uploadForm')[0]),
processData: false,
contentType: false
}).done( function(res) { }).fail( function (res) {});
url: '/upload',
type: 'POST',
cache: false,
data: new FormData($('#uploadForm')[0]),
processData: false,
contentType: false
}).done( function(res) { }).fail( function (res) {});
這里要注意幾點:
processData設置為false。因為data值是FormData對象,不需要對數據做處理。<form>標簽添加enctype="multipart/form-data"屬性。cache設置為false,上傳文件不需要緩存。contentType設置為false。因為是由<form>表單構造的FormData對象,且已經聲明了屬性enctype="multipart/form-data",所以這里設置為false。
上傳后,服務器端代碼需要使用從查詢參數名為file獲取文件輸入流對象,因為<input>中聲明的是name="file"。
如果不是用<form>表單構造FormData對象又該怎么做呢?
使用FormData對象添加字段方式上傳文件
HTML代碼
<
div
id
="uploadForm"
>
< input id ="file" type ="file" />
< button id ="upload" type ="button" >upload </ button > </ div >
這里沒有
< input id ="file" type ="file" />
< button id ="upload" type ="button" >upload </ button > </ div >
<form>標簽,也沒有
enctype="multipart/form-data"屬性。
javascript代碼
var formData =
new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url: '/upload',
type: 'POST',
cache: false,
data: formData,
processData: false,
contentType: false
}).done( function(res) { }).fail( function (res) {});
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url: '/upload',
type: 'POST',
cache: false,
data: formData,
processData: false,
contentType: false
}).done( function(res) { }).fail( function (res) {});
這里有幾處不一樣:
append()的第二個參數應是文件對象,即$('#file')[0].files[0]。contentType也要設置為‘false’。
從代碼$('#file')[0].files[0]中可以看到一個<input type="file">標簽能夠上傳多個文件,
只需要在<input type="file">里添加multiple或multiple="multiple"屬性。
