W3docs

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.

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

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


import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.File;
import java.io.IOException;

@GetMapping("/download")
public ResponseEntity<FileSystemResource> downloadFile(@RequestParam("filename") String fileName) throws IOException {
    String filePath = "/path/to/files/" + fileName;
    File file = new File(filePath);

    MediaType mediaType = MediaTypeFactory.getMediaType(file.getName())
            .orElse(MediaType.APPLICATION_OCTET_STREAM);

    FileSystemResource resource = new FileSystemResource(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, resolved using MediaTypeFactory.
  • The correct Content-Length header based on the file's size.
  • The file's contents wrapped in a FileSystemResource 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.