Spring Boot 2.X 实现文件上传(三)
使用 SpringBoot 项目完成单个、多个文件的上传处理,并将上传的文件保存到指定目录下。
代码演示案例
所有的 HTML 页面文件
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>选择上传文件类型</title>
</head>
<script language="javascript">
function single() {
document.form1.action = "/singlefile";
document.form1.submit();
}
function multi() {
document.form1.action = "/multifile";
document.form1.submit();
}
</script>
<body>
<form name="form1" method="post">
<input type="button" name="btn1" value="单个文件上传" onclick="single();">
<input type="button" name="btn2" value="多个文件上传" onclick="multi();">
</form>
</body>
</html>
multifile.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>多文件上传</title>
</head>
<body>
<h1 th:inlines="text">多文件上传</h1>
<form action="/multiFileUpload" method="post" enctype="multipart/form-data">
<p>选择文件1: <input type="file" name="fileName"/></p>
<p>选择文件2: <input type="file" name="fileName"/></p>
<p>选择文件3: <input type="file" name="fileName"/></p>
<p><input type="submit" value="提交"/></p>
</form>
</body>
</html>
singlefile.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>单文件上传</title>
</head>
<body>
<h1 th:inlines="text">单文件上传</h1>
<form action="/singleFile" method="post" enctype="multipart/form-data">
<p>文件:<input type="file" name="head_img"/></p>
<p><input type="submit" value="上传"/></p>
</form>
</body>
</html>
逻辑代码
定义结果集
@Getter
@Setter
@ToString
public class Result implements Serializable {
private boolean flag; //是否成功
private Integer code; //返回码
private String message;//返回信息
public Result(boolean flag, Integer code, String message) {
this.flag = flag;
this.code = code;
this.message = message;
}
}
定义错误码
public class StatusCode {
public static final int OK = 2000; //成功
public static final int ERROR = 4000; //失败
}
逻辑代码
@Controller
@Slf4j
public class FileController {
@Value("${file.path}")
private String filePath;
// 获取 singlefile.html 页面
@RequestMapping(value = "/singlefile", method = RequestMethod.POST)
public String single() {
return "singlefile";
}
// 单文件上传
@RequestMapping(value = "singleFile")
@ResponseBody
public Result uploadFile(@RequestParam("head_img") MultipartFile file, HttpServletRequest request) {
if (file.isEmpty()) {
return new Result(false, StatusCode.ERROR, "上传的文件大小为空,请检查!!");
}
//获取文件名称、后缀名、大小
String fileName = file.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
long size = file.getSize();
log.info("上传的文件名称为:[{}],文件后缀为:[{}],文件大小为:[{}]!!", fileName, suffixName, size);
// 存储转换后文件名称
fileName = UUID.randomUUID() + suffixName;
log.info("转换后的文件名为:[{}]!!", fileName);
File dest = new File(filePath + fileName);
//判断父目录是否存在
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest);
return new Result(true, StatusCode.OK, "上传成功!!");
} catch (IOException e) {
log.error("上传文件过程中发生异常!", e);
}
return new Result(true, StatusCode.ERROR, "上传失败!!");
}
// 获取 multifile.html 页面
@RequestMapping("/multifile")
public String multi() {
return "multifile";
}
// 多文件上传
@PostMapping(value = "multiFileUpload")
@ResponseBody
public Result multiFileUpload(HttpServletRequest request) {
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("fileName");
for (MultipartFile file : files) {
if (file.isEmpty()) {
return new Result(false, StatusCode.ERROR, "上传多个文件时,某个文件大小为空,请检查!!");
} else {
String fileName = file.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
long size = file.getSize();
log.info("上传的文件名称为:[{}],文件后缀为:[{}],文件大小为:[{}]!!", fileName, suffixName, size);
fileName = UUID.randomUUID() + suffixName;
log.info("转换后的文件名为:[{}]!!", fileName);
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest);
} catch (IOException e) {
log.error("上传文件过程中发生异常!!", e);
}
}
}
return new Result(true, StatusCode.OK, "上传成功!!");
}
}
application.properties
# 端口
server.port=8082
# 配置单个文件、多个文件大小
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB
# 文件上传保存路径
file.path=E:/test/
# 取消模板文件缓存
spring.thymeleaf.cache=false
文件 结构目录