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
       .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

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.setContentDispositionFormData("attachment", null);

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