springboot打成jar包後文件下載問題

首先springboot項目使用內置tomcat打成jar包後如果將文件放在resource下 需要使用 如下方式讀取

        InputStream inputStream = null;
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        Resource resource=resourceLoader.getResource("classpath:excel/aaaa.xlsx");
        logger.info(resource.toString());
        BufferedInputStream bis=null;
        try {
            inputStream=resource.getInputStream();
            String fileName="aaaa.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();
                }
            }
        }

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章