jquery 上传多个文件
概述
本文介绍如何利用 jquery 上传多个文件,以及后台如何接收上传的这多个文件。虽然 jquery 在当前的 web 大环境中早就日薄西山,但是还是会有一些老项目中会用到。
页面部分
文件1:<input type="file" class="file-input" name="file">
文件2: <input type="file" class="file-input" name="file">
后台接收文件部分
服务端接收部分,以 spring 为例,接收方法如下:
@PostMapping("/upload")
@ResponseBody
public void uploadFiles(@RequestParam("file") MultipartFile[] files) {
// do something to the uploaded files
}
JS 部分
let formData = new FormData();
let files = $(".file-input");
// 遍历文件输入框,将文件加入到 formData
files.each(function() {
formData.append("file", $(this)[0].files[0]);
});
$.ajax({
url: '/upload',
type: "post",
data: formData,
contentType: false,
processData: false,
dataType: "json",
mimeType: "multipart/form-data",
success: function (response) {
},
error: function () {
}
});
这里有两个地方需要注意,contentType 的值为 false, processData 的值也需要是 false,具体原因可以参考 Stackoverflow:
It’s imperative that you set the contentType option to false, forcing jQuery not to add a Content-Type header for you, otherwise, the boundary string will be missing from it. Also, you must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
如果想上传文件的时候带上文件名,可以先通过 File 对象的 name 属性获取文件名,formData 的 append 方法第三个参数可以传入文件名:
let formData = new FormData();
let files = $(".file-input");
// 遍历文件输入框,将文件加入到 formData
files.each(function() {
let files = $(this)[0].files;
if (files.length > 0) {
let filename = files[0].name;
formData.append("file", files[0], filename);
}
});
有问题吗?点此反馈!
温馨提示:反馈需要登录