简体   繁体   中英

download uploaded file using spring mvc abstractions (avoid using raw HttpServletResponse)

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?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM