1. 修改SpringBoot默认文件上传大小
servlet:
multipart:
max-file-size: 10MB
2.
@Configuration public class WebConfig implements WebMvcConfigurer { /** * 虚拟路径配置 * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/upload/**").addResourceLocations("file:F:/tomcat-upload/"); } }
3. 文件上传类
import lombok.Data; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; @Data public class UploadUtil { //源文件名 private String originalFilename; //源文件后缀名 private String suffix; //存入数据库里的tomcat虚拟路径 private String dbPath; //文件大小 private long size; //实际存储路径 private String realPath; /** * 文件上传工具类 * @param attach * @param request * @param uploader 文件上传者 * @return */ public boolean doUpload(MultipartFile attach, HttpServletRequest request, String uploader){ if(!attach.isEmpty()){ originalFilename = attach.getOriginalFilename(); System.out.println("==>上传的文件名:"+originalFilename); suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); System.out.println("==>上传的文件后缀名:"+suffix); size = attach.getSize(); System.out.println("==>上传文件的大小:"+size); String currentFilename = System.currentTimeMillis()+ UUID.randomUUID().toString() + suffix; System.out.println("==>存储的上传文件名:"+currentFilename); realPath = "F:/tomcat-upload"+request.getContextPath() +"/" + uploader + "/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()); System.out.println("==>上传文件保存的真实路径:"+realPath); File targetFile = new File(realPath, currentFilename); if(!targetFile.exists()){ targetFile.mkdirs(); } try{ attach.transferTo(targetFile); }catch (Exception e){ e.printStackTrace(); return false; } realPath = realPath + "/" + currentFilename; dbPath = "/upload" + request.getContextPath() + "/" + uploader + "/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + currentFilename; return true; }else{ return false; } } }
4. 前端上传页面
<form th:action="@{/controller-url}" method="post" enctype="multipart/form-data"> <input type="file" name="file"/><br><br> <input type="submit" value="Upload"/> <p style="color: red" th:text="${#request.getAttribute('msg')}"></p> </form>
5. 控制器
/** * 测试单文件上传 * @param file * @param request * @param session * @return */ @PostMapping("/controller-url") public String testUpload(@RequestParam(value = "file",required = false)MultipartFile file,HttpServletRequest request,HttpSession session){ UploadUtil uploadUtil = new UploadUtil(); //从session域中获取上传用户 String uploader = ((User)(session.getAttribute("currentUser"))).getUsername(); if(uploadUtil.doUpload(file,request,uploader)){ //处理上传逻辑 request.setAttribute("msg","上传成功!"); }else{ request.setAttribute("msg","上传失败!"); } return "view-url"; }