springmvc + freemark實現html生成而且下載html

/**
 * 根據ftl文件生成html文件
 */
public void buildFreemarkTemplate(UserBaseInfoModel userBaseInfo){
    Configuration configure = new Configuration(Configuration.VERSION_2_3_22);
    configure.setDefaultEncoding("utf-8");
    try {
        //加載須要裝填的模板
        Template template = null;
        //加載模板文件
        configure.setClassForTemplateLoading(this.getClass(), "/template");
        //設置異常處理器
        configure.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
        template = configure.getTemplate("test.ftl");
        //生成後的地址
        String path = HttpRequestUtil.getApplicationContextPath() + docCardPath + File.separator + userBaseInfo.getUserId() + File.separator;
        String filePath = path + userBaseInfo.getLastName() + "_" + userBaseInfo.getFirstName() + ".html";
        //不存在文件夾建立文件夾
        File createFile = new File(path);
        if(!createFile.exists()){
            createFile.mkdirs();
        }
        File outFile = new File(filePath);
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
        //設置ftl裏面的參數
        Map map = new HashMap();
        map.put("userBaseInfo", userBaseInfo);
        template.process(map, out);
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (TemplateException e) {
        e.printStackTrace();
    }
}

 

/**
 * 文件打包下載
 * @param userBaseInfo
 * @param response
 * @return
 * @throws Exception
 */
public void downLoadFiles(UserBaseInfoModel userBaseInfo,HttpServletResponse response) throws Exception {
    try {
        //圖片和html路徑
        String htmlPath = HttpRequestUtil.getApplicationContextPath() + docCardPath + File.separator + userBaseInfo.getUserId() + File.separator;
        //圖片和html路徑
        String imgagePath = HttpRequestUtil.getApplicationContextPath() + imageCardPath + File.separator + userBaseInfo.getUserId() + File.separator;
        List<File> files = new ArrayList<>();
        files.add(new File(htmlPath + userBaseInfo.getLastName() + "_" + userBaseInfo.getFirstName() + ".html"));
        //圖片1
        if(StringUtils.isNotBlank(userBaseInfo.getCardPicName1())){
            files.add(new File(imgagePath + userBaseInfo.getCardPicName1()));
        }
        //圖片2
        if(StringUtils.isNotBlank(userBaseInfo.getCardPicName2())){
            files.add(new File(imgagePath + userBaseInfo.getCardPicName2()));
        }

        File file = new File(htmlPath + File.separator + userBaseInfo.getLastName() + "_" + userBaseInfo.getFirstName() + ".zip");
        if (!file.exists()){
            file.createNewFile();
        }
        response.reset();
        //response.getWriter()
        //建立文件輸出流
        FileOutputStream fous = new FileOutputStream(file);
        /**打包的方法咱們會用到ZipOutputStream這樣一個輸出流,
         * 因此這裏咱們把輸出流轉換一下*/
        ZipOutputStream zipOut = new ZipOutputStream(fous);
        /**這個方法接受的就是一個所要打包文件的集合,
         * 還有一個ZipOutputStream*/
        zipFile(files, zipOut);
        zipOut.close();
        fous.close();
        //將zipfile和html file都傳過去
        downloadZip(file, files.get(0), response);
    }catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * 把接受的所有文件打成壓縮包
 * @param files
 * @param outputStream
 */
public static void zipFile(List files,ZipOutputStream outputStream) {
    int size = files.size();
    for(int i = 0; i < size; i++) {
        File file = (File) files.get(i);
        zipFile(file, outputStream);
    }
}

/**
 * 下載zip包
 * @param file
 * @param fileHtml
 * @param response
 * @return
 */
public static void downloadZip(File file,File fileHtml,HttpServletResponse response) {
    try {
        // 以流的形式下載文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();

        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");

        //若是輸出的是中文名的文件,在此處就要用URLEncoder.encode方法進行處理
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }finally{
        try {
            //File f = new File(file.getPath());
            //f.delete();
            if(fileHtml != null){
                File fHtml = new File(fileHtml.getPath());
                fHtml.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

/**
 * 根據輸入的文件與輸出流對文件進行打包
 * @param inputFile
 * @param ouputStream
 */
public static void zipFile(File inputFile, ZipOutputStream ouputStream) {
    try {
        if(inputFile.exists()) {
            /**若是是目錄的話這裏是不採起操做的,
             * 至於目錄的打包正在研究中*/
            if (inputFile.isFile()) {
                FileInputStream IN = new FileInputStream(inputFile);
                BufferedInputStream bins = new BufferedInputStream(IN, 512);
                //org.apache.tools.zip.ZipEntry
                ZipEntry entry = new ZipEntry(inputFile.getName());
                ouputStream.putNextEntry(entry);
                // 向壓縮文件中輸出數據
                int nNumber;
                byte[] buffer = new byte[512];
                while ((nNumber = bins.read(buffer)) != -1) {
                    ouputStream.write(buffer, 0, nNumber);
                }
                // 關閉建立的流對象
                bins.close();
                IN.close();
            } else {
                try {
                    File[] files = inputFile.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        zipFile(files[i], ouputStream);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
相關文章
相關標籤/搜索