27/04/2019

[Spring Boot] Upload file

In Spring Boot 2, your controller can expose a POST method to accept a file upload and return a JSON response simply as such:

 @RequestMapping(value="/upload", method=RequestMethod.POST, consumes = {"multipart/form-data"}, produces=MediaType.APPLICATION_JSON_VALUE)  
 @Transactional  
 public ResponseEntity<String> uploadFile(@ModelAttribute FileUploadRequest fileUploadRequest) {  
   
  fileUploadRequest.getFile(); //@TODO do something with your file  
   
  return new ResponseEntity<String>("{\"result\":\"success\"}", HttpStatus.OK);  
 }  
   
   
   
 @InitBinder  
 protected void initBinder(HttpServletRequest request,  
              ServletRequestDataBinder binder)   
 throws ServletException {  
  binder.registerCustomEditor(byte[].class,  
                new ByteArrayMultipartFileEditor());  
 }  


And the FileUploadRequest class looks something like this:

 @Accessors(chain = true)  
 @AllArgsConstructor  
 @NoArgsConstructor  
 public class FileUploadRequest {  
   private String fileName;  
   private byte[] file;  
 }  


With all the magic annotations coming from Lombok, Gradle configuration will look like this:

annotationProcessor "org.projectlombok:lombok:VERSION"
compileOnly "org.projectlombok:lombok:VERSION"

No comments:

Post a Comment

With great power comes great responsibility