使用 spring mvc 在资源文件中下载 .xlsx 文件

Download .xlsx file in the resourses file with spring mvc

我想下载存在于资源文件中的 templete.xlsx 的副本,但下载的文件已损坏。

插件:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
<configuration>
   <encoding>${project.build.sourceEncoding}</encoding>
   <nonFilteredFileExtensions>
   <nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
   </nonFilteredFileExtensions>
</configuration>
</plugin>

控制器:

 @RequestMapping(value = "download/{fileName}")
    public void downloadTemplateFile(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {

        try {
            Path templateFilePath = Paths.get(getClass().getClassLoader().getResource(fileName).toURI());
            if (Files.exists(templateFilePath)) {
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.addHeader("Content-Disposition", "attachment; filename=".concat(fileName));
                Files.copy(templateFilePath, response.getOutputStream());
                response.getOutputStream().flush();
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

当我使用 FileCopyUtils.copy 和 BufferedInputStream 而不是 Files.copy 时问题解决了,如下所示:

 response.reset();
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.addHeader("Content-Disposition", "attachment; filename=".concat(fileName));
                FileCopyUtils.copy(new BufferedInputStream(new FileInputStream(templateFilePath.toFile())), response.getOutputStream());
                response.getOutputStream().flush();
                response.getOutputStream().close();