上传界面:
<form method="post" action="路径" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" value="提交">
</form>
<!--
提交方式必须为post
enctype属性必须为multipart/form-data
后台方法接收MultipartFile变量名字要与文件选择的name属性一致,可以都写为file
-->
控制器:
@PostMapping("/upload")
public String upload(MultipartFile file, HttpServletRequest request) throws IOException {
//获取绝对路径
//String realPath = request.getServletContext().getRealPath("/files");这个是服务器的临时目录,不推荐
String realPath = ResourceUtils.getURL("classpath:").getPath()+"/static/files";
System.out.println(realPath);
File dir = new File(realPath);
if(!dir.exists()) {
//如果路径不存在就创建文件夹
dir.mkdir();
}
//文件相关信息
System.out.println(file.getName());//文件名
System.out.println(file.getSize());//文件大小
System.out.println(file.getContentType());//文件类型
file.transferTo(new File(dir,file.getOriginalFilename()));//文件上传
return "redirext:index";//不重定向的话表单会重复提交
}
修改配置文件的允许上传最大文件大小,不写默认为10MB:
# 不写单位的话默认是以字节为单位
# 服务器最大文件大小
spring.servlet.multipart.max-file-size=500MB
# 文件上传最大大小
spring.servlet.multipart.max-request-size=500MB
文件上传控制器优化:
@PostMapping("/upload")
public String upload(MultipartFile file, HttpServletRequest request) throws IOException {
//获取绝对路径
String realPath = ResourceUtils.getURL("classpath:").getPath()+"/static/files";
//按日期放置文件
String dateDir = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
File dir = new File(realPath,dateDir);
if(!dir.exists()) {
//如果路径不存在就创建文件夹
dir.mkdir();
}
//修改文件名
//前缀
String newFileNamePrefix = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+ UUID.randomUUID().toString();
//后缀
/*
需要引入依赖
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
*/
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
String newFileName = newFileNamePrefix+"."+extension;
file.transferTo(new File(dir,newFileName));//文件上传
return "redirect:index";
}