1

I am trying to add file uploading and downloading in my web application.

I am used to don't use raw HttpServletRequest and HttpServletResponse when I use spring mvc. But now I have following controller to download files.

public ModelAndView download(HttpServletRequest request,  HttpServletResponse response) throws Exception {
    int id = ServletRequestUtils.getRequiredIntParameter(request, "id");

    Files file = this.filesService.find(id);

    response.setContentType(file.getType());
    response.setContentLength(file.getFile().length);
    response.setHeader("Content-Disposition","attachment; filename=\"" + file.getFilename() +"\"");

    FileCopyUtils.copy(file.getFile(), response.getOutputStream());

    return null;

}

As you can see I use HttpServletRequest and HttpServletResponse here.

I want to find way to avoid using of these classes. Is it possible?

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710
  • 3
    This is a duplicate of [Downloading a file from spring controllers](http://stackoverflow.com/questions/5673260/downloading-a-file-from-spring-controllers). The second solution (rather than the accepted one) is the one that you want. – Steve C Dec 04 '14 at 01:41
  • Why don't you post it here? – gstackoverflow Dec 08 '14 at 06:19

1 Answers1

0

The id parameter that you are getting from request can be substituted with the use of @RequestParam or @PathVariable. See bellow for an example of @RequestParam

public ModelAndView download(@RequestParam("id") int id) {
   // Now you can use the variable id as Spring MVC has extracted it from the HttpServletRequest 
   Files file = this.filesService.find(id); // Continue from here...
}

And now the response part

@RequestMapping(value = "/download")
public ResponseEntity<byte[]> download(@RequestParam("id") int id) throws IOException
{   
    // Use of http headers....
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

    InputStream is // Get your file contents read into this input stream
    return new ResponseEntity<byte[]>(IOUtils.toByteArray(is), headers, HttpStatus.CREATED);
}
Arun
  • 526
  • 4
  • 13