赞
踩
在本机测试都很顺利,当打包jar文件放到服务器上测试的时候发现了类似下面的异常信息:
java.nio.file.NoSuchFileException: file:/xxx.jar!/BOOT-INF/classes!/xxx.xlsx
原因:springboot 将项目打包为jar,使用 java - jar 包名 在服务器上运行。此时文件为打包文件,所以不能通过路径获取到文件。类似不能读取压缩包中的文件,必须先解压缩。springboot 中的文件只能通过流来进行读取。
可以通过以下方法进行流的读取。
InputStream in = this.getClass().getClassLoader().getResourceAsStream("xxx.xlsx");
当打包jar文件放到服务器上时下载完文件提示文件损坏,代码如下
- @GetMapping("/excelOut")
- public Object templateDownload(HttpServletResponse response) {
- try {
- // 以流的形式下载文件 这种方法,打成jar包之后,下载的文件,会被损坏
- InputStream fis = FileUtil.getResourcesFileInputStream("templates/excel/template.xlsx"); //修改文件地址
- byte[] buffer = new byte[fis.available()];
- fis.read(buffer);
- fis.close();
- response.setHeader("Content-Disposition", "attachment;filename=template.xlsx");
- //response.setContentType("application/zip");
- response.setContentType("application/binary;charset=ISO8859-1");
- ServletOutputStream out = response.getOutputStream();
- out.write(buffer);
- out.flush();
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
-
- public class FileUtil {
-
- public static InputStream getResourcesFileInputStream(String fileName) {
- return Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
- }
- }

这种方法应该大部分人的问题能解决掉了,少部分人的还是解决不了,那估计就是环境的问题;我就是在这遇到这个坑,使用这种方法,ide下正常,打成jar包之后,服务器又文件损坏, 打成的jar包里面的资源文件拷贝出来,打开是正常的,说明文件打包是正常的,问题出在读取文件,或者输出流写出文件那块,还好,之前做数据导入导出的时候,有过类似的经验,于是想了其他方法。
对于Excel文件处理分为Excel模板文件根据.xls跟.xlsx类型,分别指定一下,使用XSSFWorkbook跟HSSFWorkbook即可,这里以XSSFWorkbook为例,其中资源文件放到resource目录下即可,非必须static目录:
- public void templateDownload(HttpServletResponse response) {
- try {
- InputStream fis = UUID.getResourcesFileInputStream("templates/excel/template.xlsx");
- XSSFWorkbook workbook = new XSSFWorkbook(fis);
- response.setContentType("application/binary;charset=ISO8859-1");
- String fileName = java.net.URLEncoder.encode("tm_speaker", "UTF-8");
- response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");
- ServletOutputStream out = null;
- out = response.getOutputStream();
- workbook.write(out);
- out.flush();
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- //关闭文件输出流
- }
- return;
- }

这种方法是我解决了springboot打成jar包之后服务器下载excel文件正常后的方法,在此记录一下。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。