为什么下载的文件已损坏?

时间:2016-07-05 01:38:58

标签: spring spring-mvc

我的webapp正在使用Spring MVC。下面的端点允许用户下载文件。当用户将文件(Chrome,MSIE)保存在浏览器中时,它会被破坏。它的大小是28792字节而不是24567,内容似乎有不同的编码。我花了一天时间试图解决这个问题,但没有成功。源文件工作正常。请指教。非常感谢!

@RequestMapping(method = POST, consumes = MULTIPART_FORM_DATA_VALUE)
public void processFile(MultipartFile file, HttpServletResponse response) {
    try {
        response.setHeader("Content-Encoding","UTF-8");
        Files.copy(Paths.get("c:\\files", "worksheet.xls"), response.getOutputStream());
        response.getOutputStream().flush();
    } catch (Exception ignore) {
    }
}

3 个答案:

答案 0 :(得分:1)

如果您确实要下载文件,我认为您应该像这样设置headerresponse

response.setHeader("Content-Encoding", "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=worksheet.xls");
response.setContentType("application/octet-stream");

答案 1 :(得分:0)

我发现问题出现在JavaScript on the page我用来确保自动下载。出于某种原因,它打破了文件编码。 我终于解决了这个问题,因此我没有将数据写入响应输出流,而是将其存储在临时文件中并提供了一个链接。然后我用jQuery FileDownload plugin下载它。它工作正常。

答案 2 :(得分:0)

As stated in converter, it is possible that your ResponseEntity is "converted". Look up configuration, for example in WebMvcConfigurerAdapter. If any converter is used especially default ones (like json or xml): put a break marker at every converter class write method to find out which converter is used.

相关问题