I have a system built with Spring Framework 3 and now I must implement a file download. To execute the "donwload action" I usually get the HttpServletReponse object, set the headers and get the user outputstream from it.
It works well, but I'd like to know if there's an easier/smarter way to do it?
Many thanks!
In Spring's approach to building RESTful web services, HTTP requests are handled by a controller. What is Controller ? Controller is, thread-safe class, capable of handling multiple HTTP requests throughout the lifecycle of an application.
You can use @ResponseBody
and return a byte[]
@RequestMapping("/getImage")
@ResponseBody
public byte[] getImage(HttpServletResponse response) throws IOException {
File imageFile = new File("image.jpg");
byte[] bytes = org.springframework.util.FileCopyUtils.copyToByteArray(imageFile);
response.setHeader("Content-Disposition", "attachment; filename=\"" + imageFile.getName() + "\"");
response.setContentLength(bytes.length);
response.setContentType("image/jpeg");
return bytes;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With