繁体   English   中英

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

controller:

 @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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM