Download a File from Spring Boot Rest Service

download a file from Spring boot rest service

Option 1 using an InputStreamResource

Resource implementation for a given InputStream.

Should only be used if no other specific Resource implementation is > applicable. In particular, prefer ByteArrayResource or any of the file-based Resource implementations where possible.

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

// ...

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

return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}

Option2 as the documentation of the InputStreamResource suggests - using a ByteArrayResource:

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

// ...

Path path = Paths.get(file.getAbsolutePath());
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}

How to download files from a third party Rest end point in Java

If you don't want to use additional dependecies other than jdk, you can use something like this:

URL url = new URL("http://localhost:8080/secure/attachment/1461863/fileName.txt");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");

if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}

Downloading a file from spring controllers

@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
public void getFile(
@PathVariable("file_name") String fileName,
HttpServletResponse response) {
try {
// get your file as InputStream
InputStream is = ...;
// copy it to response's OutputStream
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
} catch (IOException ex) {
log.info("Error writing file to output stream. Filename was '{}'", fileName, ex);
throw new RuntimeException("IOError writing file to output stream");
}

}

Generally speaking, when you have response.getOutputStream(), you can write anything there. You can pass this output stream as a place to put generated PDF to your generator. Also, if you know what file type you are sending, you can set

response.setContentType("application/pdf");

Downloading huge files from spring boot REST service

The code of the RestController is working as expected with a small memory footprint (the file is never loaded to the main memory completely).

The client code that works for me (also with a small memory footprint) can be found here.

Spring : Download file from REST controller

I modify the 'download' method with stream and it works correctly like I want.

public void download(Integer id, HttpServletResponse response){
Line line = getById(Line.class, id);
InputStream is = line.getFile().getBinaryStream;
IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
}

And my controller was like that :

public ResponseEntity<?> download(@RequestParam("id") Integer id, HttpServletResponse response)
{
lineService.download(id,response);
return new ResponseEntity<>(HttpStatus.OK);
}

Spring boot rest service to download a zip file which contains multiple file

Use these Spring MVC provided abstractions to avoid loading of whole file in memory.
org.springframework.core.io.Resource & org.springframework.core.io.InputStreamSource

This way, your underlying implementation can change without changing controller interface & also your downloads would be streamed byte by byte.

See accepted answer here which is basically using org.springframework.core.io.FileSystemResource to create a Resource and there is a logic to create zip file on the fly too.

That above answer has return type as void, while you should directly return a Resource or ResponseEntity<Resource> .

As demonstrated in this answer, loop around your actual files and put in zip stream. Have a look at produces and content-type headers.

Combine these two answers to get what you are trying to achieve.



Related Topics



Leave a reply



Submit