jar包内的文件导出的注意点

1.截取文件名 windows 和linux 通用

        String fp[] = filePath.replaceAll("\\\\","/").split("/");
        String fileName = filePath;
        if (fp.length > 1) {
            fileName = fp[fp.length - 1];
        }

2.文件名称转码

        response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes(),"iso-8859-1"));

3.直接按路径下载会报这样的错误

product-controller-0.0.1-SNAPSHOT.jar!\BOOT-INF\classes!\template\text.xls (No such file or directory)

解决方案

不读取工程中的文件地址,直接将对应文件转化为二进制流进行操作。

InputStream is = null;
        is = AppUtil.class.getClassLoader().getResourceAsStream(filePath);

4.附完整文件下载代码

public static void download(HttpServletResponse response, String filePath) throws IOException {


        String fp[] = filePath.replaceAll("\\\\","/").split("/");
        String fileName = filePath;
        if (fp.length > 1) {
            fileName = fp[fp.length - 1];
        }
        //下载机器码文件
        response.setHeader("conent-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes(),"iso-8859-1"));

        OutputStream os = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(os);
        InputStream is = null;
        is = AppUtil.class.getClassLoader().getResourceAsStream(filePath);
        BufferedInputStream bis = new BufferedInputStream(is);

        int length = 0;
        byte[] temp = new byte[1 * 1024 * 10];

        while ((length = bis.read(temp)) != -1) {
            bos.write(temp, 0, length);
        }
        bos.flush();
        bis.close();
        bos.close();
        is.close();
    }

猜你喜欢

转载自www.cnblogs.com/zhucww/p/9208936.html