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
  • 123
  • 2
  • 11

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,625
  • 7
  • 34
  • 65