What is the best way to create a load controller on Spring MVC?

I have a system built using Spring Framework 3, and now I have to implement the file upload. To perform the donwload action, I usually get an HttpServletReponse object, set the headers and get the output stream from it.

This works well, but I would like to know if there is an easier / smarter way to do this?

Many thanks!

+6
spring-mvc download controller action
source share
4 answers

You can use @ResponseBody and return 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; } 
+8
source share

You can use @ResponseBody or return HttpEntity from your controller method. See http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html#mvc-ann-responsebody for more details.

+2
source share

With spring mvc, you can pass OutputStream and HttpEntity as parameters, but passing the HttpServletResponse method to the controller is a great approach.

0
source share

There are other ways, but they are from the point of view of the architect / designer or the point of software development, which may or may not be easier / smarter. If you ask a designer, he can say that the controller should not know about data loading (models). Some may even recommend not using the HttpServletReponse in the controller, and some of them recommend extending the AbstractView (or choosing a suitable subclass) so that it can be reused or clear the stream in the response body to separate the view from the controller.

There may be other ways, but my recommendation is to keep it simple and implement everything that works in a team - although I would recommend checking with a designer / architect (if any) to avoid rework, as they may have another perspective.

0
source share

All Articles