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/...服务器