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);
}
Answer from fateddy on Stack OverflowOption 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);
}
The below Sample code worked for me and might help someone.
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
@RequestMapping("/app")
public class ImageResource {
private static final String EXTENSION = ".jpg";
private static final String SERVER_LOCATION = "/server/images";
@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(@RequestParam("image") String image) throws IOException {
File file = new File(SERVER_LOCATION + File.separator + image + EXTENSION);
HttpHeaders header = new HttpHeaders();
header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=img.jpg");
header.add("Cache-Control", "no-cache, no-store, must-revalidate");
header.add("Pragma", "no-cache");
header.add("Expires", "0");
Path path = Paths.get(file.getAbsolutePath());
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));
return ResponseEntity.ok()
.headers(header)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(resource);
}
}
java - How to download file from url using Spring MVC? - Stack Overflow
java - Downloading a file from spring controllers - Stack Overflow
spring mvc - How to download file from a URL and save/replace it in a folder using Java 8? - Stack Overflow
java - Spring: how to download file? - Stack Overflow
Videos
Try this:
@RequestMapping(value="/viewAttach", method = RequestMethod.GET)
public ModelAndView viewAttach(@RequestParam(value="article_id", required = true) String article_ref, HttpSession session, HttpServletResponse response)
{
/* *** Check Session *** */
try {
// Direclty from pier.content.GetContent written by ang94402
URL url = new URL(binaryURL);
response.setHeader("Content-disposition", "attachment;filename=" + binary.getName());
//Set the mime type for the response
response.setContentType("application/pdf");
// URLConnection connection = url.openConnection();
InputStream is = url.openStream();
BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
int len;
byte[] buf = new byte[1024];
while ( (len = is.read(buf)) > 0 ) {
outs.write(buf, 0, len);
}
outs.close();
} catch (MalformedURLException e) {
logger.error("Error ModelAndView.viewMain - MalformedURLException : " + e.toString() + " -- " + e.getStackTrace()[0].toString());
return null;
} catch (IOException e) {
logger.error("Error ModelAndView.viewMain - IOException : " + e.toString() + " -- " + e.getStackTrace()[0].toString());
return null;
}
return null;
}
This is just a pseudo code. Change it as per your needs.
InputStream is = getClass().getResourceAsStream("filename");
First try to figure out that getClass() points to which directory.(Not sure, but it should be HOME of your App ?). Then place your file into same location, if its not.
Hope this would help. source
@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");
I was able to stream line this by using the built in support in Spring with it's ResourceHttpMessageConverter. This will set the content-length and content-type if it can determine the mime-type
@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
@ResponseBody
public FileSystemResource getFile(@PathVariable("file_name") String fileName) {
return new FileSystemResource(myService.getFileFor(fileName));
}
In your controller method you can add this code to get file download
File file = new File("fileName");
FileInputStream in = new FileInputStream(file);
byte[] content = new byte[(int) file.length()];
in.read(content);
ServletContext sc = request.getSession().getServletContext();
String mimetype = sc.getMimeType(file.getName());
response.reset();
response.setContentType(mimetype);
response.setContentLength(content.length);
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
org.springframework.util.FileCopyUtils.copy(content, response.getOutputStream());
You don't have to know how to get the path, because the path is defined by the user :) But if your looking for the download path, check the source code of the website and where the download button links to. Usually you can see it in the beginning of the <form>.
If you are just looking for download a file:
public void download(String filename, String url) {
URL u;
InputStream is = null;
DataInputStream dis;
String s;
try{
u = new URL(url);
// throws an IOException
is = u.openStream();
dis = new DataInputStream(new BufferedInputStream(is));
FileWriter fstream = new FileWriter(filename);
BufferedWriter out = new BufferedWriter(fstream);
while ((s = dis.readLine()) != null) {
// Create file
out.write(s);
//Close the output stream
out.close();
}
}catch (Exception e){ //Catch exception if any
System.err.println("Error: " + e.getMessage());
}
is.close();
}
Hope this helps...
You need to use a HTTP client to download the file you want to proxy. Here is some example how you can do this. This example uses the Apache HTTP client 4.5.
@RequestMapping(path = "/downloadFile", method = RequestMethod.GET)
public ResponseEntity download(String param) throws IOException {
String testFileName = "https://www.google.co.jp/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(testFileName);
request.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
request.setHeader("Pragma", "no-cache");
request.setHeader("Expires", "0");
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode()==200) {
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(response.getEntity().getContent());
} else {
return ResponseEntity.notFound();
}
}
Path path = Path.resolve(fileName).normalize();
Resource resource = new UrlResource(path.toUri());
Try using this.