Thursday, December 23, 2021

Spring Boot File Download Example

 From  below  documentations  have  good  articles  about   file  download .

 

 

  • https://javadeveloperzone.com/spring-boot/spring-boot-download-file-example/


  • Basically there is no need to add produces = "application/pdf" in RequestMapping as it seems to try to convert the ResponeBody internally. You can just add MediaType to response headers which is what you need.
@ResponseBody
@RequestMapping(value = "get/pdf/{id}", headers="Accept=*/*", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> getPdfContractById(@PathVariable("id") Long id){
        // Get the remove file based on the fileaddress
        RemoteFile remotefile = new RemoteFile(id);

        // Set the input stream
        InputStream inputstream = remotefile.getInputStream();
        // asume that it was a PDF file
        HttpHeaders responseHeaders = new HttpHeaders();
        InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
        responseHeaders.setContentLength(contentLengthOfStream);
        responseHeaders.setContentType(MediaType.valueOf("application/pdf"));
        // just in case you need to support browsers
        responseHeaders.put("Content-Disposition", Collections.singletonList("attachment; filename=somefile.pdf"))
        return new ResponseEntity<InputStreamResource> (inputStreamResource,
                                   responseHeaders,
                                   HttpStatus.OK);
}
Reference :- https://stackoverflow.com/a/33877513/5802185 

No comments:

Post a Comment

Some interesting things to explore more

 Here  some  some  things  to  study  more ,     How Google Search works               https://developers.google.com/search/docs/fundamental...