zoukankan      html  css  js  c++  java
  • springboot打成jar包后文件下载问题

    首先springboot项目使用内置tomcat打成jar包后如果将文件放在resource下 需要使用 如下方式读取

    因为打成jar包后资源文件是在jar包里的,通过File获取资源绝对路径是不能访问到jar包里面的,因此使用ResourceLoader去获取文件。

    InputStream inputStream = null;
            ResourceLoader resourceLoader = new DefaultResourceLoader();
            Resource resource=resourceLoader.getResource("classpath:file/毒品价格模板.xlsx");
            logger.info(resource.toString());
            BufferedInputStream bis=null;
            try {
                inputStream=resource.getInputStream();
                String fileName="毒品价格模板.xlsx";
                response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
                response.addHeader(HttpHeaders.CONTENT_TYPE,"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                BufferedOutputStream bos = new BufferedOutputStream(
                        response.getOutputStream());
                bis = new BufferedInputStream(inputStream);
                byte[] b=new byte[1024];
                int i = bis.read(b);
                while (i != -1) {
                    bos.write(b, 0, b.length);
                    bos.flush();
                    i = bis.read(b);
                }
            } catch (IOException e) {
                e.printStackTrace();
    
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
  • 相关阅读:
    jzoj3294. 【SHTSC2013】超级跳马
    jzoj3243. Cube
    jzoj3242. Spacing
    jzoj3232. 【佛山市选2013】排列
    jzoj3297. 【SDOI2013】逃考
    jzoj4800. 【GDOI2017模拟9.24】周末晚会
    学习burnside、polya小结
    学习splay或spaly小结
    一个初学者的辛酸路程-了解Python-2
    一个初学者的辛酸路程-初识Python-1
  • 原文地址:https://www.cnblogs.com/fangyan1994/p/12887422.html
Copyright © 2011-2022 走看看