springboot获取jar包中的文件以及下载文件功能

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;
    }

通过以上代码即可完成 文件下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值