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

 

你可能感兴趣的:(springboot获取jar包中的文件以及下载文件功能)