Spring文件上传

蚊子 2022年08月16日 919次浏览

  1. <dependency>
  2. <groupId>commons-lang</groupId>
  3. <artifactId>commons-lang</artifactId>
  4. <version>2.6</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>commons-io</groupId>
  8. <artifactId>commons-io</artifactId>
  9. <version>2.4</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>commons-fileupload</groupId>
  13. <artifactId>commons-fileupload</artifactId>
  14. <version>1.2.2</version>
  15. </dependency>

  16. <dependency>
  17. <groupId>org.hibernate.validator</groupId>
  18. <artifactId>hibernate-validator</artifactId>
  19. <version>6.1.5.Final</version>
  20. </dependency>

控制器

  1. /*
  2. value = "/myupload"是路由地址
  3. method = RequestMethod.POST 规定POST请求
  4. */
  5. @RequestMapping(value = "/myupload", method = RequestMethod.POST)
  6. public String myupload(MultipartFile photo, HttpSession session) {
  7. //获取浏览器上传的文件名称
  8. String filename = photo.getOriginalFilename();
  9. //获取文件后缀
  10. String suffix = filename.substring(filename.lastIndexOf("."));
  11. //重新瓶装文件名称
  12. filename = UUID.randomUUID().toString() + suffix;
  13. System.out.println(filename);
  14. //获取项目的存储路径, 并在上下文中创建photo的文件夹
  15. String path = session.getServletContext().getRealPath("photo");
  16. System.out.println(path);
  17. File file = new File(path);
  18. //不存在就创建路径
  19. if (!file.exists()) {
  20. file.mkdir();
  21. }
  22. //F:\apache-tomcat-8.5.75\webapps\ROOT\photo\0b4800c3-76ec-4d6d-a262-b52875b89033.txt
  23. filename = path + "/" + filename;
  24. File updatefile = new File(filename);
  25. try {
  26. //执行文件上传
  27. photo.transferTo(updatefile);
  28. } catch (IOException e) {
  29. e.printStackTrace();
  30. }
  31. return "index";
  32. }