【问题标题】:download uploaded file using spring mvc abstractions (avoid using raw HttpServletResponse)使用 spring mvc 抽象下载上传的文件(避免使用原始 HttpServletResponse)
【发布时间】:2014-11-28 21:06:49
【问题描述】:

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

当我使用 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

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

【问题讨论】:

标签: java file spring-mvc io download


【解决方案1】:

您从request 获得的id 参数可以替换为@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);
}

【讨论】:

  • 您正在将整个文件加载到内存中。此解决方案不会扩展
猜你喜欢
  • 2020-02-20
  • 1970-01-01
  • 2013-05-01
  • 1970-01-01
  • 2018-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多