springboot 打包成jar 下载文件失败
jar:file:/usr/project/jar/scmp-7684.jar!/BOOT-INF/classes!/receiptTemplate/ZTEReceipt.doc
代码如下
String downloadPath = "receiptTemplate/purchaseOrder.xlsx";
String fileName = "采购数据导入模板.xlsx";
ClassPathResource classPathResource = new ClassPathResource(downloadPath);
//获取File对象 ,在本地可以,打包成jar 后获取 File对象失败
File file = classPathResource.getFile();
HttpServletResponse response = FileUtils.getDownloadResponse(fileName);
//输出文件到前台
FileUtils.writeBytes(file, response.getOutputStream());
错误原因
classPathResource.getFile() 在加载资源时 无法从jar里面加载文件。 在本地时 加载的是本地下的文件。
解决办法:
/**
获取文件输入流对象,再用输出流写出
*/
String downloadPath = "receiptTemplate/purchaseOrder.xlsx";
String fileName = "采购数据导入模板.xlsx";
//FileUtils.getDownloadResponse 为自己封装的工具类 在下面列出来了
HttpServletResponse response = FileUtils.getDownloadResponse(fileName);
ClassPathResource classPathResource = new ClassPathResource(downloadPath);
InputStream inputStream = null;
try {
//获取文件输入流 对象
inputStream = classPathResource.getInputStream();
// 进行流copy IOUtils 为 org.apache.commons.io.IOUtils 的工具类
IOUtils.copy(inputStream, response.getOutputStream());
//写出流
response.flushBuffer();
}catch (Exception e){
throw new CustomException("下载模板失败,请稍后再试");
}finally {
IOUtils.closeQuietly(inputStream);
}
/**
FileUtils.getDownloadResponse 工具类
*/
public static HttpServletResponse getDownloadResponse(String fileName){
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
response.setCharacterEncoding("utf-8");
response.setContentType("application/octet-stream");
response.setHeader("fileName", encodingFilename(fileName));
return response;
}
通过以上代码即可完成 文件下载