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

场景:springboot打成jar包,类中获取jar包中/static/***.pdf文件

本地测试没问题,路径完全没问题,但是服务器启动路径会带叹号,不知道原因为什么?有知道的小伙伴可以留个言哦。

原以为是叹号的问题,replace掉不管用。

// /applications/xxx.jar!/BOOT-INF/classes!/ -- --不知道为什么会带个叹号
File path = new File(ResourceUtils.getURL("classpath:").getPath());
File file = new File(path + "/static/" + fileName + ".pdf");
fis = new FileInputStream(file);
response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
IOUtils.copy(fis, response.getOutputStream());
response.flushBuffer();

改成下面的方式就ok了,不用去获取file,获取inputstream就好

@RequestMapping(value = "/download/{fileName}")
    public void downloadFile(@PathVariable String fileName, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding(request.getCharacterEncoding());
        response.setContentType("application/octet-stream");
        FileInputStream fis = null;
        try {
            ClassPathResource classPathResource = new ClassPathResource("static/" + fileName + ".pdf");
            InputStream inputStream = classPathResource.getInputStream();
            try {
                IOUtils.copy(inputStream, response.getOutputStream());
                response.flushBuffer();

            } finally {
                IOUtils.closeQuietly(inputStream);
            }
            /*File path = new File(ResourceUtils.getURL("classpath:").getPath());
            File file = new File(path + "/static/" + fileName + ".pdf");
            fis = new FileInputStream(file);
            response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
            IOUtils.copy(fis, response.getOutputStream());
            response.flushBuffer();*/
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

这种方式我们项目中用不到,只是看别的项目用到了记录一下,最好数据文件和jar包是分开的,将文件的路径配置到jar的***.properties中,这样读取文件的方式更好。

下面的代码只适用于下载固定模板。

1、将模板路径配置到jar包之外的某个文件夹下

2、读取配置文件

3、可以支持下载中文文件名

@Value("${urldate.importModel}")
    private String importModel;

    /**
     * 下载导入模板
     *
     * @return
     */
    @RequestMapping(value = "/downImportModelFile", produces = "application/json")
    @ResponseBody
    public Result downImportModelFile(HttpServletRequest request, HttpServletResponse response) {
        Result result = downFile(importModel, request, response);
        return result;
    }
/**
     * 下载文件
     *      下载中英文件名的文件
     * @param filePath 文件路径
     * @return
     */
    public Result downFile(String filePath, HttpServletRequest request, HttpServletResponse response) {
        InputStream fis = null;
        OutputStream toClient = null;
        File file = new File(filePath);
        if(!file.exists()){
            return Result.error("file exists");
        }
        try {
            // 以流的形式下载文件。
            fis = new BufferedInputStream(new FileInputStream(filePath));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            // 设置Response
            setResponse(request,response,file);
            toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error();
        } finally {
            try {
                if (null != fis) {
                    IOUtils.closeQuietly(fis);
                }
                if (null != toClient) {
                    toClient.flush();
                    IOUtils.closeQuietly(toClient);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
 /**
     * 设置response
     * @param request
     * @param response
     * @param file
     */
    public void setResponse(HttpServletRequest request,HttpServletResponse response,File file) {
        ServletContext sc = request.getSession().getServletContext();
        String fileName = file.getName();
        String filePath = file.getPath();
        // 清空response
        response.reset();
        // 设置response的Header
//        response.setHeader("Content-Disposition",
//                "attachment;filename="+ new String(fileName.getBytes(),"ISO8859-1"));
        response.setHeader("Content-Disposition","attachment;filename*=UTF-8''"+ URLEncoder.encode(fileName));
        response.addHeader("Content-Length", "" + file.length());
        response.setContentType(sc.getMimeType(filePath));
    }

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值