【代码】SpringBoot+AJAX上传多个文件

前言

SpringBoot+AJAX上传多个文件

前端代码

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
<input type="file" id="FileUpload" multiple>
<input type="button" value="上传" onclick="doUpload()">

<script>
function CreateFileName(upLoadFile, obj){
for(let i = 0; i < obj.files.length; i++){
upLoadFile.append("fileImages",obj.files[i]); // 这里的 "File" 需要和服务端的接收参数一致。不然会报错。
}
return upLoadFile;
}
function doUpload() {
// 发送ajax请求。
$.ajax({
url:"/fileUpload",
type:"POST",
data: CreateFileName(new FormData(),$("#FileUpload")[0]),
contentType: false,
processData: false,
success: function (data) {
alert(data);
}
});
}
</script>

后端代码

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
@RestController
public class FileController {

@RequestMapping("/fileUpload")
public String fileUpload(MultipartFile[] fileImages) throws IOException {
for (MultipartFile fileImage : fileImages) {
System.out.println("后端接到数据");
//1.获取图片名称
String name = fileImage.getOriginalFilename();
//2.准备文件上传目录
String dir = "~/Downloads/images";
//3.利用对象封装路径
File dirFile = new File(dir);
if(!dirFile.exists()){
//如果不存在,则应该创建目录
dirFile.mkdirs(); //创建多级目录
}
//4.实现文件上传
File file = new File(dir+"/" +name);
fileImage.transferTo(file);
}
return "操作成功!!!";
}

}

完成

参考文献

CSDN——FaceToBook