1.本文只提供了一個功能的代碼
public String addFreeMarker() throws Exception { HttpSession session = request.getSession(); User user = (User) session.getAttribute(Constant.USER_SESSION_KEY); String realName = user.getRealName(); System.out.println("--------獲取登錄用戶信息:------------"+realName); /* 截取后綴名 */ if (StringUtil.isEmpty(fileName)) { throw new Exception("文件不能為空"); } int pos = fileName.lastIndexOf("."); String str = fileName.substring(pos+1).toLowerCase(); //判斷上傳文件必須是zip或者是rar否則不允許上傳 if (StringUtil.isEmpty(str)||(!str.equals("zip")&&!str.equals("rar")&&!str.equals("png")&&!str.equals("jpg")&&!str.equals("gif"))) { throw new Exception("上傳文件格式錯誤,請重新上傳"); } // 時間加后綴名保存 saveName = new Date().getTime() + "."+str; //文件名 saveFileName = saveName.substring(0, saveName.lastIndexOf(".")); // 根據服務器的文件保存地址和原文件名創建目錄文件全路徑 File imageFile = new File(ServletActionContext.getServletContext() .getRealPath("upload") + "/" +saveFileName+"/"+ saveName); File descFile = new File(ServletActionContext.getServletContext().getRealPath("upload")+"/"+saveFileName); if (!descFile.exists()) { descFile.mkdirs(); } //解壓目的文件 String descDir = ServletActionContext.getServletContext().getRealPath("upload")+"/"+saveFileName+"/"; copy(myFile, imageFile); //自己生成主鍵 Long seqNo = freemarkerService.getOrderNumberSeq(); String orderNumber = RandomIdGenerator.generatorOrderNumber(seqNo); HttpServletRequest httpRequest=(HttpServletRequest)request; String httpURL = "http://" + request.getServerName() //服務器地址 + ":" + request.getServerPort() //端口號 + httpRequest.getContextPath(); //項目名稱 String URL = httpURL+"/"+"upload"+"/"+saveFileName+"/"+saveName; System.out.println("============訪問地址是:============="+ URL); //獲取用戶信息 freemarker.setFilesId(orderNumber); freemarker.setAuthor(realName); freemarker.setFilesName(saveFileName); freemarker.setFilesUrl(URL); //開始解壓zip if (str.equals("zip")) { CompressFileUits.unZipFiles(imageFile, descDir); //文件解壓成功后,把數據插入到數據庫 freemarkerService.save(freemarker); }else if (str.equals("rar")) { //開始解壓rar CompressFileUits.unRarFile(imageFile.getAbsolutePath(), descDir); freemarkerService.save(freemarker); } else if (str.equals("jpg") || str.equals("png") || str.equals("gif")) { /** * 增家java創建html功能,根據指定模板創建html */ freemarkerService.save(freemarker); //上傳的如果是圖片的話,就生成html String disrPath = ServletActionContext.getServletContext().getRealPath("template"); String sourcedir = disrPath+"/template.html"; //文件的http的路徑 String IMAGEURL = httpURL+"/"+"template"+"/"+saveFileName+".html"; //saveFileName 是文件的上傳的文件名稱 CreateHtmlUtils.MakeHtml(sourcedir, URL, disrPath, saveFileName); freemarkerDetailService.insertFreeMarkerDetailFile(orderNumber,saveFileName+".html",IMAGEURL,new Date()); } else { throw new Exception("文件格式不正確不能解壓"); } //遍歷文件夾 getFileList(descDir,orderNumber); return SUCCESS; }
2.然后是文件解壓的兩個類
package com.tydic.eshop.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipFile; import com.github.junrar.Archive; import com.github.junrar.rarfile.FileHeader; public class CompressFileUits { /** * 解壓到指定目錄 * @param zipPath * @param descDir * @author*/ public static void unZipFiles(String zipPath,String descDir)throws IOException{ unZipFiles(new File(zipPath), descDir); } /** * 解壓文件到指定目錄 * @param zipFile * @param descDir * @author isea533 */ @SuppressWarnings("rawtypes") public static void unZipFiles(File zipFile,String descDir)throws IOException{ File pathFile = new File(descDir); if(!pathFile.exists()){ pathFile.mkdirs(); } ZipFile zip = new ZipFile(zipFile); for(Enumeration entries = zip.getEntries();entries.hasMoreElements();){ ZipEntry entry = (ZipEntry)entries.nextElement(); String zipEntryName = entry.getName(); InputStream in = zip.getInputStream(entry); String outPath = (descDir+zipEntryName).replaceAll("\\*", "/");; //判斷路徑是否存在,不存在則創建文件路徑 File file = new File(outPath.substring(0, outPath.lastIndexOf('/'))); if(!file.exists()){ file.mkdirs(); } //判斷文件全路徑是否為文件夾,如果是上面已經上傳,不需要解壓 if(new File(outPath).isDirectory()){ continue; } //輸出文件路徑信息 System.out.println(outPath); OutputStream out = new FileOutputStream(outPath); byte[] buf1 = new byte[1024]; int len; while((len=in.read(buf1))>0){ out.write(buf1,0,len); } in.close(); out.close(); } System.out.println("******************解壓完畢********************"); } /** * 根據原始rar路徑,解壓到指定文件夾下. * @param srcRarPath 原始rar路徑 * @param dstDirectoryPath 解壓到的文件夾 */ public static void unRarFile(String srcRarPath, String dstDirectoryPath) { if (!srcRarPath.toLowerCase().endsWith(".rar")) { System.out.println("非rar文件!"); return; } File dstDiretory = new File(dstDirectoryPath); if (!dstDiretory.exists()) {// 目標目錄不存在時,創建該文件夾 dstDiretory.mkdirs(); } Archive a = null; try { a = new Archive(new File(srcRarPath)); if (a != null) { a.getMainHeader().print(); // 打印文件信息. FileHeader fh = a.nextFileHeader(); while (fh != null) { if (fh.isDirectory()) { // 文件夾 File fol = new File(dstDirectoryPath + File.separator + fh.getFileNameString()); fol.mkdirs(); } else { // 文件 File out = new File(dstDirectoryPath + File.separator + fh.getFileNameString().trim()); //System.out.println(out.getAbsolutePath()); try {// 之所以這么寫try,是因為萬一這里面有了異常,不影響繼續解壓. if (!out.exists()) { if (!out.getParentFile().exists()) {// 相對路徑可能多級,可能需要創建父目錄. out.getParentFile().mkdirs(); } out.createNewFile(); } FileOutputStream os = new FileOutputStream(out); a.extractFile(fh, os); os.close(); } catch (Exception ex) { ex.printStackTrace(); } } fh = a.nextFileHeader(); } a.close(); } } catch (Exception e) { e.printStackTrace(); } } }
3.常見html的工具類,上篇文章有介紹 CreateHtmlUtils
package com.tydic.eshop.util; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Calendar; /** * @ClassName: CreateHtmlUtils * @Description: Java 根據模板創建 html * @author * @date 2016年4月22日 下午3:51:16 */ public class CreateHtmlUtils { public static void main(String[] args) { String filePath = "E:\\hh_web_space\\ecp\\web\\ecp_web_page\\src\\main\\webapp\\template\\template.html"; String imagePath ="http://localhost:8080/ecp/upload/1461293787628/1461293787628.jpg"; String disrPath = "E:\\hh_web_space\\ecp\\web\\ecp_web_page\\src\\main\\webapp\\template\\"; String fileName = "liuren"; MakeHtml(filePath,imagePath,disrPath,fileName); } /** * @Title: MakeHtml * @Description: 創建html * @param filePath 設定模板文件 * @param imagePath 需要顯示圖片的路徑 * @param disrPath 生成html的存放路徑 * @param fileName 生成html名字 * @return void 返回類型 * @throws */ public static void MakeHtml(String filePath,String imagePath,String disrPath,String fileName ){ try { String title = "<image src="+'"'+imagePath+'"'+"/>"; System.out.print(filePath); String templateContent = ""; FileInputStream fileinputstream = new FileInputStream(filePath);// 讀取模板文件 int lenght = fileinputstream.available(); byte bytes[] = new byte[lenght]; fileinputstream.read(bytes); fileinputstream.close(); templateContent = new String(bytes); System.out.print(templateContent); templateContent = templateContent.replaceAll("###title###", title); System.out.print(templateContent); String fileame = fileName + ".html"; fileame = disrPath+"/" + fileame;// 生成的html文件保存路徑。 FileOutputStream fileoutputstream = new FileOutputStream(fileame);// 建立文件輸出流 System.out.print("文件輸出路徑:"); System.out.print(fileame); byte tag_bytes[] = templateContent.getBytes(); fileoutputstream.write(tag_bytes); fileoutputstream.close(); } catch (Exception e) { System.out.print(e.toString()); } } }
4.復制的方法 copy
// 復制方法 public static void copy(File src, File dst) { try { InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; while (in.read(buffer) > 0) { out.write(buffer); } } finally { if (null != in) { in.close(); } if (null != out) { out.close(); } } } catch (Exception e) { e.printStackTrace(); } }
5.便利解壓的的zip或者是rar文件夾
/** * @throws ServiceException * @Title: getFileList * @Description: 遞歸遍歷指定文件夾下的文件 * @param @param strPath * @param @return 設定文件 * @return List<File> 返回類型 * @throws */ public List<File> getFileList(String strPath,String fileordernumber) throws ServiceException { File dir = new File(strPath); File[] files = dir.listFiles(); // 該文件目錄下文件全部放入數組 List<File> fileList = new ArrayList<File>(); if (files != null) { for (int i = 0; i < files.length; i++) { String fileName = files[i].getName(); if (files[i].isDirectory()) { // 判斷是文件還是文件夾 getFileList(files[i].getAbsolutePath(),fileordernumber); // 獲取文件絕對路徑 System.out.println("輸出文件的絕對路徑"+files[i].getAbsolutePath()); } else if (fileName.endsWith("html")) { // 判斷文件名是否以.avi結尾 String strFileName = files[i].getAbsolutePath(); System.out.println("------------" + strFileName+"+++++"+fileName); // uploadcompressDetailService.insertCompressDetailFile(fileordernumber,fileName,strFileName,new Date()); freemarkerDetailService.insertFreeMarkerDetailFile(fileordernumber,fileName,strFileName,new Date()); fileList.add(files[i]); } else { continue; } } } return fileList; }
6.其中需要的架包
<!-- 導入zip解壓包 --> <dependency> <groupId>ant</groupId> <artifactId>ant</artifactId> <version>1.6.5</version> </dependency> <!-- 導入rar解壓包 --> <dependency> <groupId>com.github.junrar</groupId> <artifactId>junrar</artifactId> <version>0.7</version> </dependency>