使用spring mvc abstractions下载上传的文件(避免使用原始的HttpServletResponse)

时间:2014-11-28 21:06:49

标签: java file spring-mvc io download

我正在尝试在我的网络应用程序中添加文件上传和下载。

当我使用spring mvc时,我习惯不使用原始HttpServletRequestHttpServletResponse。但现在我有跟随控制器下载文件。

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;

}

如您所见,我在此处使用HttpServletRequestHttpServletResponse

我想找到避免使用这些类的方法。有可能吗?

1 个答案:

答案 0 :(得分:0)

您从id获取的request参数可以替换为使用@RequestParam@PathVariable。有关@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...
}

现在是响应部分

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