spring boot部署到linux服务器中使用freemark模板下载excel出现的问题

SpringBoot 项目使用浏览器从linux服务器下载文件报错java.io.FileNotFoundException:

根据项目的问题是碰到路径的问题
项目中是要配置虚拟路径

一.Controller中的方法
再application.yaml中配置linux放ftl的外部路径
在这里插入图片描述

   @Value("${update_url}")
    private String updateUrl;
  /**
     * 以freemarker生成excel(带数据)报表
     * @param response
     * @param request
     */
    @ApiOperation(value = "下载报表")
    @RequestMapping("/downLoadTemplates")
    public void downLoadTemplate_s(HttpServletResponse response, HttpServletRequest request,String name){
        try {
            Map maps = this.personnelReportService.selectByMapS(name);
            //获取文件 //也可以传入null对象参数,对应到ftl中的行数就要修改
            ExcelUtils.writeResponse(request,response,ExcelUtils.Excel_2003,name,name+".ftl",maps,updateUrl);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

二.使用到工具类的代码

public class ExcelUtils {

    public static String Excel_2007 = "Excel_2007";
    public static String Excel_2003 = "Excel_2003";

    /**
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @param version  Word_2003/Word_2007
     * @param docFileName 生成的doc临时文件名
     * @param templateFile  freemark模板文件名
     * @param beanParams  入参数据:  Map类型
     */
    public static void writeResponse(HttpServletRequest request, HttpServletResponse response, String version, String docFileName, String templateFile, Map beanParams,String updateUrl) {
        //windown中设置的路径
        //writeResponse(request, response, version, "c:/img/", docFileName, "src/main/resources/imp", templateFile, beanParams,updateUrl);
        //linux中设置的路径
        writeResponse(request, response, version, "zzsres/img", docFileName, "src/main/resources/imp", templateFile, beanParams,updateUrl);

    }


    /**
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @param version  Word_2003/Word_2007
     * @param docTempDir  生成的doc临时文件目录
     * @param docFileName 生成的doc临时文件名
     * @param templateDir 存放freemark模板的目录
     * @param templateFile freemark模板文件名
     * @param beanParams   入参数据:  Map类型
     */
    public static void writeResponse( HttpServletRequest request, HttpServletResponse response, String version, String docTempDir, String docFileName, String templateDir, String templateFile, Map beanParams,String updateUrl) {
        Configuration config = new Configuration();
        ServletContext sc = request.getSession().getServletContext();
        InputStream is = null;
        File previewFile = null;
        OutputStream stream = null;
        try {
            System.out.println("查看"+updateUrl);
            config.setDirectoryForTemplateLoading(new File(updateUrl));
            config.setObjectWrapper(new DefaultObjectWrapper());
            Template template = config.getTemplate(templateFile, "UTF-8");
            if (Excel_2007.equals(version)) {
                docFileName = docFileName + ".xlsx";
            } else {
                docFileName = docFileName + ".xls";
            }
    
            if (!EncodingUtil.getEncoding(docFileName).equals("UTF-8")) {
                docFileName = URLEncoder.encode(docFileName, "UTF-8");
            }
           
            //windown 中excel文件的临时路径
            //String docName = request.getSession().getServletContext().getRealPath("")+docFileName;
            //linux  中excel文件的临时路径  在系统报错找不到路径,最后确定是这个路径的问题
            String docName = request.getSession().getServletContext().getRealPath("")+docFileName;
            System.out.println("下载的临时文件路径"+docName);
            FileOutputStream fos = new FileOutputStream(docName);
            OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");

            template.process(beanParams, out);
            out.flush();
            out.close();

            previewFile = new File(docName);
            is = new FileInputStream(previewFile);
            response.setContentType("application/force-download");
            docFileName = new String(docFileName.getBytes("UTF-8"), "ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+docFileName);
            stream = response.getOutputStream();
            byte[] b = new byte[1024];
            int len = 0;
            while ((len=is.read(b)) != -1) {
                stream.write(b,0,len);
            }
            stream.flush();
            stream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if(is!=null){
                    is.close();
                }
                if (stream!=null) {
                    stream.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if(previewFile!=null){
                previewFile.delete();
            }
        }
    }
}

三.最后还要配springboot的虚拟路径

@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    /*
        * 说明:增加虚拟路径(经过本人测试:在此处配置的虚拟路径,用springboot内置的tomcat时有效,
        * 用外部的tomcat也有效;所以用到外部的tomcat时不需在tomcat/config下的相应文件配置虚拟路径了,阿里云linux也没问题)
        */
        //windows下  特别注意  在win环境下 路径最后一定要加“/”
        //registry.addResourceHandler("/img/**").addResourceLocations("file:c:/img/");
        //linux下
        registry.addResourceHandler("/img/**").addResourceLocations("file:///zzsres/img");
    }

}

你可能感兴趣的:(spring boot部署到linux服务器中使用freemark模板下载excel出现的问题)