实现主要逻辑
1、前端使用jquery
获取input.file
中文件内容
2、将文件逐个append
到FormData()
对象中
3、将AJAX属性processData
和contentType
设置为false
4、后端使用@RequestPart
注解和MultipartFile
对象接收文件并进行后续操作
前端代码
<div>
<input type="file" id="image" multiple /><br />
<button onclick="upload()">提交</button>
</div>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
function upload() {
let url = "http://localhost:8088/index/upload";
let formData = new FormData();
let image = $("#image")[0].files;
for (let item of image) {
formData.append("files", item);
}
$.ajax({
url: url,
method: "post",
processData: false,
contentType: false,
data: formData,
success: (res) => {
console.log(res);
}
})
}
</script>
input.file
添加multiple
属性开启多文件选择。
在使用
jQuery
的AJAX
方法的时候参数processData
默认为true
,默认情况下会将发送的数据序列化以适应默认的内容类型application/x-www-form-urlencoded
,设置为false
表示告诉jQuery
不要处理请求数据。
contentType
个人认为应该设置为multipart/form-data
,但是设置后请求体中的FormData
会变成乱码(可能是被jQuery处理了)。而设置为false
后查看开发者工具Network
时,Content-Type
会被自动设置为: multipart/form-data; boundary=----WebKitFormBoundarylAI6z8Sa8jrFjYAM
后面多加的一段字符串作用还有待探究。
后端代码
@PostMapping("/upload")
public String upload(@RequestPart("files") MultipartFile[] files) throws IOException {
if (files.length > 0) {
for (MultipartFile file : files) {
file.transferTo(new File("/Users/mars/Desktop/"+file.getOriginalFilename()));
}
}
String success = "上传成功";
return success;
}
@RequestPart
注解参数与前端传过来参数名称需要保持一致。
- 以下为官方对
@RequestPart
的解释
大概意思是:@RequestPart
这个注解用在multipart/form-data
表单提交请求的方法上。支持的方法参数为 MultipartFile
,而@RequestParam
注解也能处理多媒体上传业务。但是由于具体实现不同。@RequestParam
注解更倾向于处理名称-值
表单字段,而 @RequestPart
注解更可能用于包含更复杂内容的部分,(例如JSON
、XML
)。
当文件有多个时需要声明
MultipartFile[]
,即将若干个文件封装到MultipartFile
数组中