1.需求: 演示 Spring-Boot 通过表单注册用户,并支持上传图片
● 需求: 演示 Spring-Boot 通过表单注册用户,并支持上传图片
● 代码实现-文件上传
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>uploadtitle>
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 "注册用户成功/文件上传成功";
}
}
上面的示例中实现了文件的上传,但当两个不同的文件文件名相同时会存在文件覆盖的问题,如何解决呢?
@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;
,实现思路就是给上传的文件重新指定一个不重复的文件名
解决思路:将文件上传到不同目录 比如 一天上传的文件,统一放到 一个文件夹 年/月/日, 比如 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 "注册用户成功/文件上传成功";
}