Pages

27/04/2019

[Spring Boot] Download or display file in browser from controller

In Spring Boot 2, we can provide an endpoint that allows users to perform GET requests to download (or display) a file in their browsers as follows:

 @RequestMapping("/downloadFile/{fileId}")  
 public ResponseEntity<byte[]> downloadFile(@PathVariable("fileId") String fileId){  
  File file = null; //@TODO get your file from wherever using fileId or the logic you need  
   
  byte[] fileBytes = Files.readAllBytes(file.toPath()); //@TODO for example, but you might convert file to byte[] as you wish  
   
  HttpHeaders headers = new HttpHeaders();  
  headers.setContentType(MediaType.APPLICATION_PDF); //@TODO change accordingly!  
  headers.setContentDispositionFormData("attachment", file.getName()); //change to "inline" if you wish the browser to try do display it instead of downloading. WARNING: behaviour is browser dependent!  
  headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); //prevent caching  
  ResponseEntity<byte[]> response = new ResponseEntity<>(fileBytes, headers, HttpStatus.OK);  
  return response;  
 }  
   
   
   
 @InitBinder  
 protected void initBinder(HttpServletRequest request,  
              ServletRequestDataBinder binder)   
 throws ServletException {  
  binder.registerCustomEditor(byte[].class,  
                new ByteArrayMultipartFileEditor());  
 }  

No comments:

Post a Comment

With great power comes great responsibility