-
创建一个新模块项目
-
添加web、thymeleaf依赖
配置上传属性application.properties,指定上传文件大小限制等
#文件上传配置
spring.servlet.multipart.max-file-size=100MB
- 编写Controller,通过java.nio实现文件上传
@Controller
public class UploadController {
//遇到http://localhost:8080,则跳转至upload.html页面
@GetMapping("/")
public String index() {
return "upload";
}
@PostMapping("upload")
public String fileUpload(@RequestParam("file") MultipartFile srcFile, RedirectAttributes redirectAttributes) {
//前端没有选择文件,srcFile为空
if (srcFile.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "请选择一个文件");
return "redirect:upload_status";
}
//选择了文件,开始上传操作
try {
//构建上传目标路径,找到了项目的target的classes目录
File destFile = new File(ResourceUtils.getURL("classpath:").getPath());
if (!destFile.exists()) {
destFile = new File("");
}
SimpleDateFormat sf_ = new SimpleDateFormat("yyyyMMddHHmmss");
String times = sf_.format(new Date());
//输出目标文件的绝对路径
System.out.println("file path:" + destFile.getAbsolutePath());
//拼接子路径
File upload = new File(destFile.getAbsolutePath(), "static/" + times);
//若目标文件夹不存在,则创建
if (!upload.exists()) {
upload.mkdirs();
}
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
// 获得文件原始名称
String fileName = srcFile.getOriginalFilename();
// 获得文件后缀名称
String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
// 生成最新的uuid文件名称
String newFileName = uuid + "." + suffixName;
System.out.println("完整的上传路径:" + upload.getAbsolutePath() + "/" + newFileName);
//根据srcFile大小,准备一个字节数组
byte[] bytes = newFileName.getBytes();
//通过项目路径,拼接上传路径
Path path = Paths.get(upload.getAbsolutePath() + "/" + newFileName);
//** 开始将源文件写入目标地址
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message", "文件上传成功" + newFileName);
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:upload_status";
}
//匹配upload_status页面
@GetMapping("upload_status")
public String uploadStatusPage() {
return "upload_status";
}
}
- 控制器配置好thymeleaf的页面跳转及信息显示
<head>
<meta charset="UTF-8">
<title>Spring Boot文件上传页面</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>文件上传状态显示</title>
</head>
<body>
<h2>Spring Boot的文件上传状态</h2>
<div th:if="${message}">
<h2 th:text="${message}"/>
</div>
</body>
</html>
-
运行项目,上传文件,观察结果