Ask Question

Spring create a GET Rest Call which downloads a file

How can I implement a simple GET call which downloads a file with Spring?

SpringJava

1091 views

Authorยดs Dominik Sumer image

Dominik Sumer

Last edited on

1 Answer available

Best answer

I think the easiest solution is to use the org.springframework.core.io.Resource class provided by Spring. If you wrap it in a ResponseEntity and fill everything with your needed parameters then you should be good to go.

Here is an example:

@GetMapping(value = "/api/file/download")
public ResponseEntity<Resource> downloadFile() {
    /* getFileInputStream contains your logic for reading the file */
    InputStreamResource resource = new InputStreamResource(getFileInputStream());

    return ResponseEntity.ok()
            .header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
            .header("Content-Type", contentType) // the mimetype of your file e.g. image/png
            .contentLength(contentLength) // the size of your file
            .body(resource);
}
๐Ÿ‘
1