06.SpringBoot 之文件上传

SpringBoot 之文件上传

文件上传对于日常开发其实也比较常见的,存在于一些业务里面需要长传一些文件。比如说用户中心的用户头像,招聘App中的简历文件等。那么下面我们就来看看springboot中如何实现文件上传。

通过表单上传文件

首先,我们先使用普通的表单来上传文件。

1
2
3
4
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="提交">
</form>

后端接受和配置信息:

application.properties

1
2
3
4
5
# 文件的最大大小
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.enabled=true
# 最大请求大小
spring.servlet.multipart.max-request-size=10MB

配置类:

1
2
3
4
5
6
7
8
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//配置文件存储位置。
registry.addResourceHandler("/img/**").addResourceLocations("file:c://upload/img/");
}
}

说明:这里我们通过配置的方式来指定文件的访问路径,因为上传的文件将放在此目录下。

controller:

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
26
27
28
29
30
@RestController
public class FileUploadController {

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");

@PostMapping("/upload")
public String upload(MultipartFile file, HttpServletRequest request) {
String format = simpleDateFormat.format(new Date());
String path = "c:/upload/img/" + format;
File folder = new File(path);
if (!folder.exists()) {
folder.mkdirs();
}
String originalFilename = file.getOriginalFilename();
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
String newFileName = UUID.randomUUID().toString() + suffix;
try {
file.transferTo(new File(folder, newFileName));
String scheme = request.getScheme();//协议 http 或 https
String serverName = request.getServerName();//服务器名称
int serverPort = request.getServerPort();//服务器端口
String url = scheme + "://" + serverName + ":" + serverPort + "/img/"
+ format + newFileName;
return url;
} catch (IOException e) {
e.printStackTrace();
}
return "error";
}
}

通过Ajax上传文件

通过Ajax实现文件上传,后端代码不用修改,只需要前端有普通的表单提交修改为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
26
27
28
29
30
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script src="jquery-3.4.1.min.js"></script>
<body>
<input type="file" id="file" name="file" >
<input type="button" value="上传" onclick="uploadFile()" >
<div id="result"></div>
</body>
<script>
function uploadFile() {
var file = $("#file")[0].files[0];
var formData = new FormData();
formData.append("file",file);
$.ajax({
type:'post',
url:'/upload',
processData:false,
contentType:false,
data:formData,
success:function (msg) {
$("#result").html(msg);
}
});
}
</script>
</html>

这里通过$("#file") 获取指定id的组件,取第0个转为DOM对象。获取该DOM对象的files属性。同时只取其中的第一个文件。上传我们利用FormData对象来协助。如果有更多的属性,可以继续通过append来添加。

后端代码不需要改变。

多文件上传

1
2
3
4
5
<!--两种不同的多文件上传-->
<form action="/uploads" method="post" enctype="multipart/form-data">
<input type="file" name="files" multiple>
<input type="submit" value="提交">
</form>

上面是同一个File中支持多个文件上传,后端需要使用数组来接收。另一种多文件上传的方式就是多个单文件上传的控件。则controller形参中需要定义多个MultipartFile对象。如下:

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
26
27
28
29
30
/**
* 多文件上传。
* 如果使用的不是多文件输入框,而是多个文件输入款。则将其改为多个MultipartFile进行标识。
* public String uploads(MultipartFile file1, MultipartFile file1, HttpServletRequest request)
*/
@PostMapping("/uploads")
public String uploads(MultipartFile[] files, HttpServletRequest request) {
String format = simpleDateFormat.format(new Date());
String path = "c:/upload/img/" + format;
File folder = new File(path);
if (!folder.exists()) {
folder.mkdirs();
}
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];
String originalFilename = file.getOriginalFilename();
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));//文件后缀
String newFileName = UUID.randomUUID().toString() + suffix;//文件新名字
try {
file.transferTo(new File(path, newFileName));
String fileName = request.getScheme() + "://" + request.getServerName() + ":" +
request.getServerPort() + "/img/" + format + newFileName;
System.out.println(fileName);
} catch (IOException e) {
e.printStackTrace();
return "error";
}
}
return "success";
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×