Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream file download through RestTemplate

I have a large file download that is served by a RestController on one server, that I need to stream through a RestController on another server. When calling the end server directly the result streams fine. However when using RestTemplate to call this server and then write the response to an OutputStream, the response is buffered on the front server until the whole file is ready, and then streamed. Is there a way I can write the file to an OutputStream as it comes in?

At the moment my code on the front server looks similar to this

@ResponseBody
public void downloadResults(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") String jobId, OutputStream stream)
        throws IOException
{
    byte[] data = restTemplate.exchange("http://localhost/getFile", HttpMethod.POST, requestEntity, byte[].class, parameters).getBody();
    stream.write(data);
}

I've set my RestTemplate to not buffer and I've verified that this is working by checking the Request type that is used, (SimpleStreamingClientHttpRequest). The data all comes back correct, its just only written to the stream all at once, rather than as it comes in

like image 971
ali2992 Avatar asked Jun 21 '16 08:06

ali2992


People also ask

How do I download files from RestTemplate?

RestTemplate provides the following two ways to download a file from a remote Http url: Using byte array (holding everything in memory) Using ResponseExtractor (stream the response instead of loading it to memory)

How do I download files from server in Spring boot?

File Download in Spring Boot It is a simple GET URL and on the click of that URL the file will be downloaded automatically in the browser as we will be adding Content-Disposition in the response header as an attachment and the content type as application/octet-stream.

Why RestTemplate is deprecated?

RestTemplate provides a synchronous way of consuming Rest services, which means it will block the thread until it receives a response. RestTemplate is deprecated since Spring 5 which means it's not really that future proof. First, we create a Spring Boot project with the spring-boot-starter-web dependency.

Which is better RestTemplate or WebClient?

RestTemplate will still be used. But in some cases, the non-blocking approach uses much fewer system resources compared to the blocking one. So, WebClient is a preferable choice in those cases.


1 Answers

You can use restTemplate.execute. See https://www.baeldung.com/spring-resttemplate-download-large-file

like image 94
Prof Mo Avatar answered Sep 19 '22 12:09

Prof Mo