13.Spring Boot文件上传示例
2019-03-25 本文已影响0人
sherlockwit_孙鸣
一、创建upload模块项目
-
可按照下图顺序进行创建:
创建一个新的模块
springboot
接下来的创建方法跟之前的创建方法都一样,不过要注意这次添加web、thymeleaf依赖!!!
![](https://img.haomeiwen.com/i16493400/ea8fc9fdf295dc07.png)
二、建立包以及代码(由于创建模块时已直接添加依赖,所以无需在pom里再进行配置 )
![](https://img.haomeiwen.com/i16493400/f98126ec8e3b6b8f.png)
application.properties
#大小配置
spring.servlet.multipart.max-file-size=100MB
UploadController.java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* 上传文件控制器
* 直接上传到服务器
* Created by Administrator on 2019/3/25.
*/
@Controller
public class UploadController {
//指定一个临时路径作为上传目录
//private static String UPLOAD_FOLDER = "C:\\Users\\Liuyu\\Desktop\\UPLOAD\\";
//遇到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("");
}
//输出目标文件的绝对路径
System.out.println("file path:"+destFile.getAbsolutePath());
//拼接子路径
SimpleDateFormat sf_ = new SimpleDateFormat("yyyyMMddHHmmss");
String times = sf_.format(new Date());
File upload = new File(destFile.getAbsolutePath(), "static/"+times);
//若目标文件夹不存在,则创建
if(!upload.exists()) {
upload.mkdirs();
}
System.out.println("完整的上传路径:"+upload.getAbsolutePath()+"/"+srcFile);
//根据srcFile大小,准备一个字节数组
byte[] bytes = srcFile.getBytes();
//拼接上传路径
//Path path = Paths.get(UPLOAD_FOLDER + srcFile.getOriginalFilename());
//通过项目路径,拼接上传路径
Path path = Paths.get(upload.getAbsolutePath()+"/"+srcFile.getOriginalFilename());
//** 开始将源文件写入目标地址
Files.write(path, bytes);
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
// 获得文件原始名称
String fileName = srcFile.getOriginalFilename();
// 获得文件后缀名称
String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
// 生成最新的uuid文件名称
String newFileName = uuid + "."+ suffixName;
redirectAttributes.addFlashAttribute("message", "文件上传成 功"+newFileName);
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:upload_status";
}
//匹配upload_status页面
@GetMapping("upload_status")
public String uploadStatusPage() {
return "upload_status";
}
}
upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SpringBoot文件上传页面</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>
upload_status.html
<!DOCTYPE html>
<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>
三、观察结果
-
首先运行
显示运行成功
-
输入localhost:8080
效果页面
-
点击上传即可实现功能
页面效果
-
图片已保存到路径
image.png