今天碰到一个坑 前端调用下载Excel模板接口时,下载文件成功,但是文件被损坏。
先上代码~
@Api(tags ="xx")
@RestController
@RequestMapping("/excelRead")
@Slf4j
public class NewExcelUtil {
@ResponseBody
@RequestMapping(value ="/readExcel", method = RequestMethod.GET)
public void downloadExcel(HttpServletRequest request, HttpServletResponse response){
try {
InputStream inputStream = (InputStream)this.getClass().getClassLoader().getResourceAsStream("template/xx.xlsx");
String path =this.getClass().getClassLoader().getResourceAsStream("template/xx.xlsx").toString();
response.setContentType("application/zip");
OutputStream out = response.getOutputStream();
response.setHeader("Content-Disposition","attachment; filename=" + java.net.URLEncoder.encode("xx","UTF-8") +".xlsx");
int b =0;
byte[] buffer =new byte[1024];
while (b != -1) {
b = inputStream.read(buffer);
if (b != -1) out.write(buffer,0, b);
}
inputStream.close();
out.close();
out.flush();
}catch (IOException e) {
e.printStackTrace();
log.error("模板下载失败");
}
}
}
解决: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>
原因:
原因就是springboot的resource目录下的文件是默认自动压缩的,所有直接下载打开会出错。
这个插件可以避免xlsx文件在resource目录下被自动压缩,这样就可以正常下载,打开了
网友评论