HTML5 FormData ajax上传文件

创建对象:

var formData = new FormData();
//一般文本参数
formData.append('name', 'asd');
//File参数
formData.append('file', $('#file1')[0].files[0]);

第一种$.ajax方法提交:

$.ajax({
url: "http://192.168.2.14:3000/api/v1/fileparse",
type: 'POST',
data: formData,
/**
*必须false才会自动加上正确的Content-Type
*/
contentType:false,
*
* 必须false才会避开jQuery对 formdata 的默认处理
* XMLHttpRequest会对 formdata 进行正确的处理
processData:false
}).done(function(result){
console.log(result);
}).fail(function(err){
console.log(err);
});

第二种$.post方法提交:

//必须进行以下设置,否则提交上去的数据格式不对
$.ajaxSetup({
contentType:false, //必须false才会自动加上正确的Content-Type
processData:false //必须false才会避开jQuery对 formdata 的默认处理
});
$.post("http://192.168.2.14:3000/api/v1/fileparse", formData, function(result){
console.dir(result);
},'json');