XMLHttpRequest Level 2添加了一個新的接口FormData.利用FormData對象,咱們能夠經過JavaScript用一些鍵值對來模擬一系列表單控件,咱們還能夠使用XMLHttpRequest的send()方法來異步的提交這個"表單".比起普通的ajax,使用FormData的最大優勢就是咱們能夠異步上傳一個二進制文件。html
經過FormData對象能夠組裝一組用 XMLHttpRequest發送請求的鍵/值對。它能夠更靈活方便的發送表單數據,由於能夠獨立於表單使用。若是你把表單的編碼類型設置爲multipart/form-data ,則經過FormData傳輸的數據格式和表單經過submit() 方法傳輸的數據格式相同。html5
var formData = new FormData(FormElement);
這裏的FormElement是html元素爲form表單;固然這裏也能夠直接構造不用填寫form元素,填寫form元素的目的是能夠直接選取form中表單元素的name和value爲formData添加鍵值對。jquery
append(DOMString name, Blob value, optional DOMString filename); append(DOMString name, DOMString value);
name: 字段名稱,也就是鍵名;
value: 字段值,能夠是Blob對象,能夠是File對象,能夠是字符串,剩下其它,該值會被自動轉爲字符串;
filename: (可選)指定文件的文件名,當value參數被指定爲一個Blob對象或者一個File對象時,該文件名會被髮送到服務器上,對於Blob對象來講,這個值默認爲」blob」。ajax
<form enctype="multipart/form-data" id=」form」> <label>Your email address:</label> <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br /> <label>Custom file label:</label> <input type="text" name="filelabel" size="12" maxlength="32" /><br /> <label>File to stash:</label> <input type="file" name="file" id=」file」 required /> </form> <input type="file" name="fileother" id=」fileother」 required /> <input type="button" value="Stash the file!" id=」submit」/> <div></div>
(function(){ var file =null, fileOther=null,fd=new FormData($("#form")[0]); bindEvent(); function bindEvent(){ $("#file").change(function(){ file = this.files[0]; }); $("#fileother").change(function(){ fileOther = this.files[0]; }) $("#submit").click(function(){ fd.append("file", file); fd.append("fileother", fileOther); ajaxSend(); }) } function ajaxSend(){ $.ajax({ url: "your url", type: "post", data: fd, processData: false, // 不處理數據 contentType: false, // 不設置內容類型 success: function(resp){ console.log(resp); } }) } })()
一、https://developer.mozilla.org...
二、https://developer.mozilla.org...
三、http://www.cnblogs.com/lhb25/...服務器