Spring文件downolad - httpServeletResponse null标头和内容类型

时间:2017-11-22 08:39:09

标签: java jsp spring-mvc

我在我的spring web应用程序中有一个视图,用户可以在其中下载存储在托管项目的服务器中的文件。 因此,在此视图中,我浏览其信息显示在表中的文件列表,最后一列包含指向该文件的链接。 我的问题是,对于少数文件,HttpServletResponse内容类型和标头是以空值发送的,即使它们是在控制器的函数中设置的,浏览器也会显示application / octet-stream类型的响应。

在我的jsp页面中:

<a href="<spring:url value='/download/${file.fileid}'/>"><i class="fa fa-download" title="download"></i></a>

这是类Controller中的downolad函数的代码:

    @RequestMapping(value="/download/{fileid}", method = RequestMethod.GET)
    public void download(@PathVariable Integer fileid,  HttpServletResponse response)
    {

        File file = new   File((directoryService.findBydata("feedback").getPath()).trim()+"\\"+ (fileservice.findByfileid(fileid).getfilename()).trim());
        InputStream fis;    
        if(file.exists()){
             try {
                    fis = new FileInputStream(file);
                    org.apache.commons.io.IOUtils.copy(fis, response.getOutputStream());
                                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

                    response.setHeader("Content-Disposition",
                    "attachment; filename="+(fileservice.findByfileid(fileid).getfilename()).trim());

                    response.flushBuffer();

                    } catch (IOException e) {
                                e.printStackTrace();
                            }

                        }

}

我无法找到问题的原因,不知道为什么会这样?感谢。

1 个答案:

答案 0 :(得分:0)

HttpServletResponse的更改仅在方法退出后写入响应。

但是,您的代码会立即将文件内容写入输出流。因此,客户端在开始时没有适当的标头接收数据。

尝试将输入流包装到InputStreamResource中并返回。

@RequestMapping(value="/download/{fileid}", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> download(@PathVariable Integer fileid, HttpServletResponse response) {
    File file = new   File((directoryService.findBydata("feedback").getPath()).trim()+"\\"+ (fileservice.findByfileid(fileid).getfilename()).trim());
    if(file.exists()){
        try {
            InputStream fis = new FileInputStream(file);
            InputStreamResource inputStreamResource = new InputStreamResource(fis);

            return ResponseEntity
                    .status(HttpStatus.OK)
                    .header(HttpHeaders.CONTENT_TYPE, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+(fileservice.findByfileid(fileid).getfilename()).trim())
                    .body(inputStreamResource);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}