我想下载一个存在于资源文件中的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();
}
}
发布于 2021-05-02 21:36:40
当我使用带有BufferedInputStream的FileCopyUtils.copy而不是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();
https://stackoverflow.com/questions/67284494
复制相似问题