0

I would like to download a file while retaining the filename of the file.

I have:

    @RequestMapping(value = "/downloadFile", method = RequestMethod.GET,  produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    @ResponseBody
    public FileSystemResource getFile(@RequestParam(value="filename") String filename) {
        return new FileSystemResource(uploadDir + "/" + filename); 
    }

I can download the file but the filename I download is always 'downloadFile.pdf' or 'downloadFile.png'.

How can I retain the original filename? Thanks.

AlanBE
  • 103
  • 2
  • 10
  • duplicate of https://stackoverflow.com/questions/35680932/download-a-file-from-spring-boot-rest-service – Nitika Jun 07 '19 at 07:51

1 Answers1

1

You can try the following code in Spring.

@GetMapping(value = "/downloadFile", method = RequestMethod.GET,  produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
  public ResponseEntity<?> downloadFile(@RequestParam(value="filename") String filename) {
    String dirPath = "your-location-path";
    byte[] fileBytes = null;
    try {
      fileBytes = Files.readAllBytes(Paths.get(dirPath + fileName));
    } catch (IOException e) {
      e.printStackTrace();
    }
    return ResponseEntity.ok()
        .contentType(MediaType.APPLICATION_OCTET_STREAM)
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
        .body(fileBytes);
  }
Sambit
  • 7,063
  • 5
  • 29
  • 58