Downloading a file from spring controllers

To download a file from a Spring controller, you can use the ResponseEntity class along with the InputStreamResource class.

Here's an example of how you can do this:

@GetMapping("/download")
public ResponseEntity<InputStreamResource> downloadFile() throws IOException {
  MediaType mediaType = MediaTypeUtils.getMediaTypeForFileName(this.servletContext, fileName);

  File file = new File(filePath);
  InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

  return ResponseEntity.ok()
      .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName())
      .contentType(mediaType)
      .contentLength(file.length())
      .body(resource);
}

This code creates a ResponseEntity object with the following:

  • A content disposition header that specifies that the file should be downloaded as an attachment.
  • The correct Content-Type header based on the file's extension.
  • The correct Content-Length header based on the file's size.
  • The file's contents wrapped in an InputStreamResource object.

When the controller method is called, the browser will prompt the user to download the file.

I hope this helps! Let me know if you have any questions.