最近,在做一个springboot下载excel文件的模块,下载下来的文件一直是文件受损,网上找了一堆解决办法都不行,墨迹了半天终于解决了,主要原因就是springboot的resource目录下的文件是默认自动压缩的,所有直接下载打开会出错,这里记录一下解决方法
先上代码
public void downloadExcel(HttpServletResponse response,HttpServletRequest request) { try { //获取要下载的模板名称 String fileName = "ruleConfig.xlsx";//ruleConfig.xlsx //设置要下载的文件的名称 response.setHeader("Content-Disposition", "attachment;filename=" + fileName); //通知客服文件的MIME类型 response.setContentType("application/vnd.ms-excel;charset=UTF-8"); //获取文件的路径 String filePath = getClass().getResource("/static/" + fileName).getPath(); System.out.println(filePath); FileInputStream input = new FileInputStream(filePath.substring(1)); OutputStream out = response.getOutputStream(); byte[] b = new byte[2048]; int len; while ((len = input.read(b)) != -1) { out.write(b, 0, len); } out.flush(); out.close(); input.close(); } catch (Exception ex) { log.error("getApplicationTemplate :", ex); //return Response.ok("应用导入模板下载失败!"); } }
这就是普通的下载的代码
解决办法
重点是下面在pom中添加避免压缩的插件
<plugin> <groupId>org.apache.maven.plugins</groupId> <version>2.6</version> <artifactId>maven-resources-plugin</artifactId> <configuration> <encoding>UTF-8</encoding> <nonFilteredFileExtensions> <nonFilteredFileExtension>xlsx</nonFilteredFileExtension> </nonFilteredFileExtensions> </configuration> </plugin>
这个插件可以避免xlsx文件在resource目录下被自动压缩,这样就可以正常下载,打开了