从资源目录下获取文件流

Controller

    @PostMapping("getTemplates")
    @ResponseBody
    public ResultMoudel getTemplates(@RequestParam(required = false,defaultValue ="maintenance_import.xlsx") String name1, @RequestParam(required = false,defaultValue = "重点设备保养统计导入模板.xlsx") String name2, HttpServletResponse response) throws IOException {
        ResultMoudel resultMoudel=new ResultMoudel();
//         ExcelUtils.getResourceFile(response,"repair_import.xlsx","设备维修统计导入模板.xlsx");
        ExcelUtils.getResourceFile(response,name1,name2,null);

        return resultMoudel.success("success");
    }

Service

public static void getResourceFile(HttpServletResponse response, String templateFileName, String exportFileName,String path) throws IOException {
        log.info("开始获取资源");
        StopWatch sw = new StopWatch("开始获取资源");
        sw.start();
        if (StringUtils.isEmpty(templateFileName)) {
            throw new RuntimeException("模板名称不能为空!");
        }
        /*为空获取模板 不为空获取错误文件*/
        InputStream in=null ;
        if (path==null) {
            String excelTemplate = "excel/" + templateFileName;
            log.info("资源路径为:" + excelTemplate);
              in = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate);
        }else{
            File file =new File(path);
            if(!file.exists())
            {
                log.info("下载错误文件未找到文件");
                return;
            }
              in =new FileInputStream(file);

        }
        log.info("成功获取文件流"  );

        if (in == null) {
            throw new RuntimeException("模板" + templateFileName + "不存在!");
        }
        String urlString = null;  //输出
        try {
            urlString = URLEncoder.encode(exportFileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;fileName=" + urlString);
        response.setHeader("fileName",  urlString);
        try {
            int count = 0;
            byte[] b = new byte[count];
            b = StreamUtils.copyToByteArray(in);
            OutputStream out=response.getOutputStream();
            out.write(b);
         } catch ( IOException e) {
            e.printStackTrace();
        } finally {
            in.close();
        }
     }

就可以读取资源目录下的文件返回给前端了

从资源目录下获取文件流_第1张图片

 

你可能感兴趣的:(excel,java,开发语言)