Sending file in Spring Boot

Asked by At

I'm creating spring boot application that send a file in body response, to this i use this code :

FileSystemResource pdfFile = new FileSystemResource(outputFile);

return ResponseEntity
       .ok()
       .contentLength(pdfFile.contentLength())
       .contentType(MediaType.parseMediaType("application/pdf"))
       .body(new ByteArrayResource(IOUtils.toByteArray(pdfFile.getInputStream())));

I'm wondering if there's any alternative way for send file other than using FileSystemResource ?

Please, If there's any suggestion, do not hesitate.

Thank You !

1 Answers

1
darksmurf On Best Solutions

This is a simplified version of how I usually do it, but it does pretty much the same thing:

@RequestMapping(method = RequestMethod.GET, value = "/{id}")
public ResponseEntity<byte[]> getPdf(@PathVariable Long id) throws IOException {
    final String filePath = pdfFilePathFinder.find(id);

    final byte[] pdfBytes = Files.readAllBytes(Paths.get(filePath));

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    headers.setContentDispositionFormData("attachment", null);
    headers.setCacheControl("no-cache");

    return new ResponseEntity<>(pdfBytes, headers, HttpStatus.OK);
}