Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the best way to make a download controller on Spring MVC?

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!

like image 764
Mikhas Avatar asked Feb 28 '11 13:02

Mikhas


People also ask

Is controller thread safe in Spring?

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.


1 Answers

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;
}
like image 162
MosheElisha Avatar answered Oct 13 '22 18:10

MosheElisha