SpringBoot文件上传
我们在工作中经常会遇到文件上传的需求,本文使用SpringBoot简单实现文件上传。
首先Pom.xml
1 <dependencies> 2 <dependency> 3 <groupId>org.springframework.boot</groupId> 4 <artifactId>spring-boot-starter-web</artifactId> 5 </dependency> 6 <dependency> 7 <groupId>org.springframework.boot</groupId> 8 <artifactId>spring-boot-starter-test</artifactId> 9 <scope>test</scope> 10 </dependency> 11 <!-- thmleaf模板依赖. --> 12 <dependency> 13 <groupId>org.springframework.boot</groupId> 14 <artifactId>spring-boot-starter-thymeleaf</artifactId> 15 </dependency> 16 </dependencies>
编写Controller层
1 @Controller 2 public class FileUploadController { 3 4 private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class); 5 6 /** 7 * 跳转到单个文件上传 8 * 9 * @return 10 */ 11 @RequestMapping(value = "/upload", method = RequestMethod.GET) 12 public ModelAndView upload() { 13 return new ModelAndView("/fileUpload"); 14 } 15 16 /** 17 * 跳转到多个文件上传 18 * 19 * @return 20 */ 21 @RequestMapping(value = "/upload/batch", method = RequestMethod.GET) 22 public ModelAndView batchUpload() { 23 return new ModelAndView("/multiFileUpload"); 24 } 25 26 /** 27 * 文件上传具体实现方法(单文件上传) 28 * 29 * @param file 30 * @return 31 */ 32 @RequestMapping(value = "/upload", method = RequestMethod.POST) 33 @ResponseBody 34 public String upload(@RequestParam("file") MultipartFile file) { 35 try { 36 if (file.isEmpty()) { 37 return "文件为空"; 38 } 39 // 获取文件名 40 String fileName = file.getOriginalFilename(); 41 logger.info("上传的文件名为:" + fileName); 42 // 获取文件的后缀名 43 String suffixName = fileName.substring(fileName.lastIndexOf(".")); 44 logger.info("文件的后缀名为:" + suffixName); 45 46 // 设置文件存储路径 47 String filePath = "E://xuchen//"; 48 String path = filePath + fileName + suffixName; 49 50 File dest = new File(path); 51 // 检测是否存在目录 52 if (!dest.getParentFile().exists()) { 53 dest.getParentFile().mkdirs();// 新建文件夹 54 } 55 file.transferTo(dest); 56 return "上传成功"; 57 } catch (IllegalStateException e) { 58 e.printStackTrace(); 59 } catch (IOException e) { 60 e.printStackTrace(); 61 } 62 return "上传失败"; 63 } 64 65 /** 66 * 多文件上传 67 * 68 * @param request 69 * @return 70 */ 71 @RequestMapping(value = "/upload/batch", method = RequestMethod.POST) 72 @ResponseBody 73 public String batchUpload(HttpServletRequest request) { 74 List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file"); 75 MultipartFile file; 76 BufferedOutputStream stream; 77 for (int i = 0; i < files.size(); ++i) { 78 file = files.get(i); 79 if (!file.isEmpty()) { 80 try { 81 byte[] bytes = file.getBytes(); 82 stream = new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename()))); 83 stream.write(bytes); 84 stream.close(); 85 } catch (Exception e) { 86 stream = null; 87 return "文件上传失败 " + i + " => " + e.getMessage(); 88 } 89 } else { 90 return "文件上传失败 " + i + "原因:上传文件为空!"; 91 } 92 } 93 return "文件上传成功"; 94 } 95 }
文件上传相关配置
1 @Configuration 2 public class FileUploadConfiguration { 3 4 @Bean 5 public MultipartConfigElement multipartConfigElement() { 6 MultipartConfigFactory factory = new MultipartConfigFactory(); 7 // 设置文件大小限制 ,超出设置页面会抛出异常信息, 8 // 这样在文件上传的地方就需要进行异常信息的处理了; 9 factory.setMaxFileSize("2MB"); 10 /// 设置总上传数据总大小 11 factory.setMaxRequestSize("5MB"); 12 return factory.createMultipartConfig(); 13 } 14 }
前端页面(单个上传)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>单个文件上传</title> 6 </head> 7 <body> 8 <h2>文件上传示例</h2> 9 <hr/> 10 <form method="POST" enctype="multipart/form-data" action="/upload"> 11 <p> 12 文件:<input type="file" name="file"/> 13 </p> 14 <p> 15 <input type="submit" value="上传"/> 16 </p> 17 </form> 18 </body> 19 </html>