We often encounter the need for file uploading in our work. This article uses SpringBoot to simply implement file uploading.
First 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>
Write the Controller layer
1 @Controller 2 public class FileUploadController { 3 4 private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class ) ; 5 6 /** 7 * Jump to single file upload 8 * 9 * @return 10 */ 11 @RequestMapping (value = "/upload", method = RequestMethod.GET) 12 public ModelAndView upload() { 13 return new ModelAndView("/fileUpload" ); 14 } 15 16 /** 17 * Jump to multiple file upload 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 * The specific implementation method of file upload (single file upload) 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 "The file is empty" ; 38 } 39 // Get the file name 40 String fileName = file.getOriginalFilename(); 41 logger.info("Uploaded file name: " + fileName); 42 // Get the suffix name of the file 43 String suffixName = fileName.substring(fileName.lastIndexOf("." )); 44 logger.info("The suffix name of the file is: " + suffixName); 45 46 // Set the file storage Path 47 String filePath = "E://xuchen//" ; 48 String path = filePath + fileName + suffixName; 49 50 File dest = new File(path); 51 // Check if there is a directory 52 if (! dest.getParentFile ().exists()) { 53 dest.getParentFile().mkdirs(); // Create a new folder 54 } 55 file.transferTo(dest); 56 return "Upload successful" ; 57 } catch (IllegalStateException e) { 58 e.printStackTrace(); 59 } catch (IOException e) { 60 e.printStackTrace(); 61 } 62 return "Upload failed" ; 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 "File upload failed" + i + " => " + e.getMessage(); 88 } 89 } else { 90 return "File upload failed" + i + "Reason: Uploaded file is empty!" ; 91 } 92 } 93 return "File uploaded successfully" ; 94 } 95 }
File upload related configuration
1 @Configuration 2 public class FileUploadConfiguration { 3 4 @Bean 5 public MultipartConfigElement multipartConfigElement() { 6 MultipartConfigFactory factory = new MultipartConfigFactory(); 7 // Set the file size limit, an exception will be thrown if the setting page is exceeded, 8 // In this way The place where the file is uploaded needs to handle the exception information; 9 factory.setMaxFileSize("2MB" ); 10 // / Set the total upload data size 11 factory.setMaxRequestSize("5MB" ); 12 return factory.createMultipartConfig(); 13 } 14 }
Front-end page (single upload)
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>
Test Results
Demo source code download address: https://gitee.com/inchlifc/SpringBootTest.git