Ajax 同时提交数据和文件

Ajax 一般用于异步提交或获取数据,使用 Ajax 提交文件这种场景一般很少遇到,更不要提同时提交数据和文件的场景

前台代码

1
2
3
4
5
<form action="">
<input id="notes" type="text" />
<input id="files" type="file" multiple>
<input type="submit" />
</form>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 声明 FormData 对象
var form_data = new FormData();

// 添加数据
form_data.append("notes", $("#notes").val());

// 遍历 File 的文件
for (var i = 0; i < $("#files")[0].files.length; i++) {
form_data.append("files[" + i + "]" , $("#files")[0].files[i]);
}

// 提交
$.ajax({
type: "POST",
url: "/",
data: form_data,
processData: false,
contentType: false,
success: function (data) {
console.log("success");
},
error: function () {
console.log("error");
}
});

后台代码

1
2
3
4
5
[HttpPost]
public ActionResult Insert(string notes, HttpPostedFileBase[] files)
{
//...
}

参考

Post JSON with data AND file to Web Api - jQuery / MVC