【问题标题】:Files downloaded through a spring controller are corrupted通过 spring 控制器下载的文件已损坏
【发布时间】:2017-05-09 03:01:21
【问题描述】:

我的后端保存了 .xlsx、.docx 和 .pdf 文件。下载控制器如下所示:

@RestController
public class FileDownload {

@RequestMapping(value = "/files/{file_name}/", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void getFile(
        @PathVariable("file_name") String file,
        HttpServletResponse response) throws Exception {

        String fileType=file.split("\\.")[1];

        switch(fileType){
            case "xlsx": response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                break;
            case "docx": response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                break;
            case "pdf": response.setContentType("application/pdf");
                break;
            default: response.setContentType("application/octet-stream");
                break;
        }

        response.setHeader("Content-Disposition", "attachment; filename=" + file);
        response.setHeader("Content-Length", String.valueOf(file.length()));

        InputStream is = FileDownload.class.getResourceAsStream("/files/"  + file);

        copy(is, response.getOutputStream());
        response.flushBuffer();
}
}

当试图打开文件时,excel 告诉我它已损坏,需要修复。但是修复过程也失败了。

什么可能导致此错误?

有很多类似的问题,但建议的解决方案似乎都不起作用。

唯一有效的“修复”是将“下载”属性附加到前端下载文件的链接。但遗憾的是,这不适用于 IE。

【问题讨论】:

    标签: spring download file-type


    【解决方案1】:

    我在下载 zip 文件时遇到了同样的问题。我的解决方案最终是从我的控制器返回一个字节数组(请参阅https://stackoverflow.com/a/33302570/4921953),然后在我的 JavaScript 前端以不同的方式处理它,用于 Chrome/Firefox(我使用了您使用的下载属性)和 Internet Explorer(见https://stackoverflow.com/a/24354303/4921953)。当您从前端向服务器发出 HTTP 请求时,请确保将 responseType 设置为“arraybuffer”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多