0

I have a Controller returning an "InputStreamResource file". I want that this file appears to the downloads. It isn´t important for me to return this file to the Frontend, but when it will be neccessary I can do this. How can I start a download? Thanks!

This is my Controller with the "InputStreamResource file":

@RequestMapping(path = "/csv", method = RequestMethod.GET)
    public ResponseEntity<InputStreamResource> getCSV() {
        String filename = "User.csv";
        InputStreamResource file = new InputStreamResource(fileService.load());
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename)
                .contentType(MediaType.parseMediaType("application/csv"))
                .body(file);
    }

Here I get the csv data in my frontend:

 csv() {
    this.userService.getCSV().subscribe(
      {
        next: data =>{
          console.log(data)
        }
      }
    );
  }

output:

1,user1

2,user2

3,user3

KollegeBo
  • 45
  • 4

1 Answers1

0

I guess you need the correct headers and return type. The following example returns desired files. The only difference should be the cast InputStream to byte array(Convert InputStream to byte array in Java).

@GetMapping(value = "/{attachmentId}/attachment", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public ResponseEntity<byte[]> getImage(@PathVariable Long attachmentId) throws IOException {
    Attachment attachment = attachmentRepository.findById(attachmentId).orElseThrow(RuntimeException::new);
    byte[] file = attachment.getFile();
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    responseHeaders.set("Content-Disposition", "attachment; filename=" + attachment.getName());

    return new ResponseEntity<>(file, responseHeaders, HttpStatus.OK);
}