'how to downlod file using resttemplate
String uri = "URL";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<byte[]> response = restTemplate.exchange(uri, HttpMethod.GET, entity, byte[].class, "1");
I get response like-> <200,[B@c505096,[Pragma:"no-cache", Content-Disposition:"inline; filename=935436242330664960_pratikpopo.txt", Expires:"0", Cache-Control:"no-cache, no-store, must-revalidate", Content-Type:"application/octet-stream", Content-Length:"18", Date:"Mon, 31 Jan 2022 04:16:56 GMT"]> I want to downlod (935436242330664960_pratikpopo.txt) this file. Is there any way to download this file
Solution 1:[1]
{
URL link = new URL("your full url http://........");
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream("C:/download-file/YourFileName.txt");
fos.write(response);
fos.close();
}
Solution 2:[2]
@RequestMapping(value = "/download3/{path}", method = RequestMethod.GET)
public String downloadFile4( @RequestParam("file_name") String path) throws IOException
{
String uri = "File Path-URL(location wehere your file is stored on server)";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<byte[]> response = restTemplate.exchange(uri, HttpMethod.GET, entity, byte[].class, "1");
URL furl = new URL(uri);
ReadableByteChannel rbc = Channels.newChannel(furl.openStream());
FileOutputStream fos = new FileOutputStream("C:/download-file/"+ response.getHeaders().getContentDisposition().getFilename());
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
return "file downloaded";
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Saman Salehi |
| Solution 2 |
