上海網(wǎng)站建設(shè)方案托管銀川seo
resources
?目錄下放模板 excel 文件,通過接口下載后,可以正常下載,但打不開。
問題:?springboot
?項目簡單的下載excel
?模板功能,模板放在resources/template/
目錄中
public void downloadItemBatch(HttpServletResponse response) throws IOException {String fileName = "商品信息.xlsx";String path = "templates/" + fileName;InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);response.setContentType("application/vnd.ms-excel;charset=UTF-8");response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));ServletOutputStream outputStream = response.getOutputStream();IOUtils.copy(inputStream, outputStream);outputStream.flush();outputStream.close();inputStream.close();}
代碼挺簡單,一運行,也挺順利,很快就把文件下好了。點開看看,提示我可能是內(nèi)存不足,文件無法打開,而且下載的文件比templates里的文件要大。
看了很多帖子,試了很多方法,最后發(fā)現(xiàn),pom文件里加個東西就行了
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-resources-plugin</artifactId><version>2.7</version><configuration><nonFilteredFileExtensions><!--不加這一行,xlsx文件會被過濾,然后在maven build的時候,去target下看對應(yīng)的xlsx就是損壞的--><nonFilteredFileExtension>xlsx</nonFilteredFileExtension></nonFilteredFileExtensions></configuration>
</plugin>
解決:maven 構(gòu)建時對該 excel 模板進行了過濾,導(dǎo)致文件損壞,解決辦法,在過濾的時候把 xlsx 排除掉(<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
)。