SpringBoot文件上传功能的实现方法
1.应用实例
需求: 演示 Spring-Boot 通过表单注册用户,并支持上传图片
2.代码实现
代码实现-文件上传
创建 templates/upload.html , 要求头像只能选择一个, 而宠物可以上传多个图片
<!DOCTYPE html>
<
html
lang
=
"en"
xmlns:th
=
"http://www.thymeleaf.org"
>
<
head
>
<
meta
charset
=
"UTF-8"
>
<
title
>upload</
title
>
</
head
>
<
body
bgcolor
=
"#CED3FE"
>
<
img
src
=
"images/1.GIF"
/>
<
hr
/>
<
div
style
=
"text-align: center"
>
<
h1
>注册用户~</
h1
>
<
form
action
=
"#"
th:action
=
"@{/upload}"
method
=
"post"
enctype
=
"multipart/form-data"
>
用户名:<
input
type
=
"text"
style
=
"width:150px"
name
=
"name"
/><
br
/><
br
/>
电 邮:<
input
type
=
"text"
style
=
"width:150px"
name
=
"email"
/><
br
/><
br
/>
年 龄:<
input
type
=
"text"
style
=
"width:150px"
name
=
"age"
/><
br
/><
br
/>
职 位:<
input
type
=
"text"
style
=
"width:150px"
name
=
"job"
/><
br
/><
br
/>
头 像:<
input
type
=
"file"
style
=
"width:150px"
name
=
"header"
><
br
/><
br
/>
宠 物:<
input
type
=
"file"
style
=
"width:150px"
name
=
"photos"
multiple><
br
/><
br
/>
<
input
type
=
"submit"
value
=
"注册"
/>
<
input
type
=
"reset"
value
=
"重新填写"
/>
</
form
>
</
div
>
<
hr
/>
</
body
>
</
html
>
2.创建src\main\java\com\llp\springboot\controller\UploadController.java
@Slf4j
@Controller
public
class
UploadController {
//处理转发到用户注册-可以完成文件上传页面
@GetMapping
(
"/upload.html"
)
public
String uploadPage() {
return
"upload"
;
// 视图解析,转发到templates/upload.html
}
@PostMapping
(
"/upload"
)
@ResponseBody
public
String upload(
@RequestParam
(
"name"
) String name,
@RequestParam
(
"email"
) String email,
@RequestParam
(
"age"
) Integer age,
@RequestParam
(
"job"
) String job,
@RequestParam
(
"header"
) MultipartFile header,
@RequestParam
(
"photos"
) MultipartFile[] photos)
throws
IOException {
log.info(
"name:{},email:{},age:{},job:{},header.size:{},photos.length:{}"
,name,email,age,job,header.getSize(),photos.length);
//1.获取源文件名称
String originalFilename = header.getOriginalFilename();
// /E:/IdeaProjects/springboot-sysuser/target/classes/
String path = ResourceUtils.getURL(
"classpath:"
).getPath();
System.out.println(path);
File file =
new
File(path+
"static/images/upload/"
);
if
(!file.exists()){
file.mkdirs();
}
header.transferTo(
new
File(path+
"static/images/upload/"
+originalFilename));
return
"注册用户成功/文件上传成功"
;
}
}
3.引出两个问题
1.文件覆盖问题
上面的示例中实现了文件的上传,但当两个不同的文件文件名相同时会存在文件覆盖的问题,如何解决呢?
@PostMapping
(
"/upload"
)
@ResponseBody
public
String upload(
@RequestParam
(
"name"
) String name,
@RequestParam
(
"email"
) String email,
@RequestParam
(
"age"
) Integer age,
@RequestParam
(
"job"
) String job,
@RequestParam
(
"header"
) MultipartFile header,
@RequestParam
(
"photos"
) MultipartFile[] photos)
throws
IOException {
log.info(
"name:{},email:{},age:{},job:{},header.size:{},photos.length:{}"
,name,email,age,job,header.getSize(),photos.length);
//1.获取源文件名称
String originalFilename = header.getOriginalFilename();
originalFilename = UUID.randomUUID().toString().replaceAll(
"-"
,
""
)+System.nanoTime()+originalFilename;
//2.获取文件上传的路径
// /E:/IdeaProjects/springboot-sysuser/target/classes/
String path = ResourceUtils.getURL(
"classpath:"
).getPath();
System.out.println(path);
//3.动态的创建文件上传目录
File file =
new
File(path+
"static/images/upload/"
);
if
(!file.exists()){
file.mkdirs();
}
//4.将文件传输到目标目录
header.transferTo(
new
File(path+
"static/images/upload/"
+originalFilename));
return
"注册用户成功/文件上传成功"
;
}
originalFilename = UUID.randomUUID().toString().replaceAll("-","")+System.nanoTime()+originalFilename;
,实现思路就是给上传的文件重新指定一个不重复的文件名
2.将文件都上传到一个目录下,当上传文件很多时,会造成访问文件速度变慢
解决思路:将文件上传到不同目录 比如 一天上传的文件,统一放到 一个文件夹 年/月/日, 比如 2022/11/11 目录
public
class
WebUtils {
//定义一个文件上传的路径
public
static
String UPLOAD_FILE_DIRECTORY =
"static/images/upload/"
;
//编写方法,生成一个目录-根据当前日期 年/月/日
public
static
String getUploadFileDirectory() {
return
UPLOAD_FILE_DIRECTORY +
new
SimpleDateFormat(
"yyyy/MM/dd"
).format(
new
Date());
}
}
@PostMapping
(
"/upload"
)
@ResponseBody
public
String upload(
@RequestParam
(
"name"
) String name,
@RequestParam
(
"email"
) String email,
@RequestParam
(
"age"
) Integer age,
@RequestParam
(
"job"
) String job,
@RequestParam
(
"header"
) MultipartFile header,
@RequestParam
(
"photos"
) MultipartFile[] photos)
throws
IOException {
//输出获取到的信息
log.info(
"上传的信息 name={} email={} age={} job={} header={} photos={} "
,
name, email, age, job, header.getSize(), photos.length);
//得到类路径(运行的时候)
String path = ResourceUtils.getURL(
"classpath:"
).getPath();
//log.info("path={}", path);
//动态创建指定目录
File file =
new
File(path + WebUtils.getUploadFileDirectory());
if
(!file.exists()) {
//如果目录不存在,我们就创建, 在java io
file.mkdirs();
}
if
(!header.isEmpty()) {
//处理头像
//获取上传文件的名字
String originalFilename = header.getOriginalFilename();
String fileName = UUID.randomUUID().toString() +
"_"
+ System.currentTimeMillis() +
"_"
+ originalFilename;
//保存到动态创建的目录
header.transferTo(
new
File(file.getAbsolutePath() +
"/"
+ fileName));
}
//处理多个文件
if
(photos.length >
0
) {
for
(MultipartFile photo : photos) {
//遍历
if
(!photo.isEmpty()) {
String originalFilename = photo.getOriginalFilename();
String fileName = UUID.randomUUID().toString() +
"_"
+ System.currentTimeMillis() +
"_"
+ originalFilename;
//保存到动态创建的目录
photo.transferTo(
new
File(file.getAbsolutePath() +
"/"
+ fileName));
}
}
}
return
"注册用户成功/文件上传成功"
;
}
到此这篇关于SpringBoot文件上传功能的实现方法的文章就介绍到这了
参考文章:http://blog.ncmem.com/wordpress/2023/11/21/springboot%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0%e5%8a%9f%e8%83%bd%e7%9a%84%e5%ae%9e%e7%8e%b0%e6%96%b9%e6%b3%95/
欢迎入群一起讨论