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);//开始解压zipif (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);//上传的如果是图片的话,就生成htmlString 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>            

Java解压上传zip或rar文件,并解压遍历文件中的html的路径相关推荐

  1. 解压上传zip文件并获取excel表数据

    1.maven <!-- 解压rar --><dependency><groupId>com.github.junrar</groupId><ar ...

  2. java流式上传下载_精讲RestTemplate第6篇-文件上传下载与大文件流式下载

    C++Templates(第2版英文版) 123.24元 (需用券) 去购买 > 本文是精讲RestTemplate第6篇,前篇的blog访问地址如下: 精讲RestTemplate第1篇-在S ...

  3. java的图片上传与前端展示实例(Servlet+Jsp)

    java的图片上传与前端展示实例(Servlet+Jsp) 内容前瞻 1.关于路径 2.前端图片上传与展示 3.后台获取并保存 环境 1.前端jsp 2.服务器tomcat 3.服务端servlet ...

  4. web上传zip大文件,java服务接收并解压ZIP文件

    目录 一.背景 二.知识点 三.代码实现 1.依赖 2.web 代码 3. java服务端 一.背景 公司产品小伙伴画了原型后,需要上传到服务器上供开发查看:由于文件数量很多,100M左右差不多要传3 ...

  5. java spring mvc 上传_Java Spring MVC 上传下载文件配置及controller方法详解

    下载: 1.在spring-mvc中配置(用于100M以下的文件下载) 下载文件代码 @RequestMapping("/file/{name.rp}") public Respo ...

  6. java上传下载_Java文件上传与文件下载实现方法详解

    本文实例讲述了Java文件上传与文件下载实现方法.分享给大家供大家参考,具体如下: Java文件上传 数据上传是客户端向服务器端上传数据,客户端向服务器发送的所有请求都属于数据上传.文件上传是数据上传 ...

  7. java压缩包加密上传,解密下载

    java压缩包加密上传,解密下载 业务场景 供应商上传投标文件需要进行加密处理,通过链接下载时下载的时加密的文件,而通过系统内访问接口下载时,下载的是解密好的文件. 问题解决思路 1. 首先配置三个保 ...

  8. java多图片上传插件,Bootstrap中的fileinput 多图片上传及编辑功能

    Bootstrap中的fileinput 多图片上传及编辑功能 2019-01-01 编程之家收集整理的这篇文章主要介绍了Bootstrap中的fileinput 多图片上传及编辑功能,编程之家小编觉 ...

  9. 网络安全与渗透:文件上传漏洞,一文详解(十)此生无悔入华夏,男儿何不带吴钩

    中华人民共和国网络安全法 阅读本文前,请熟读并遵守中华人民共和国网络安全法: http://gkhy.jiujiang.gov.cn/zwgk_228/jc/zcwj/202006/P02020061 ...

最新文章

  1. 解决大众点评换设备无法用卷(你本次购买不符合活动规则)的问题
  2. iOS获取webView的内容或修改网页上的内容
  3. php 数组格式的字符串转为数组_php将字符串转换为数组实例讲解
  4. c语言填空三个数找中间大小,2013计算机等级考试二级C语言填空题.doc
  5. python 库列表_python库安装列表
  6. MySQL 多实例详解
  7. SQL Server 2008安装配置说明书+简单使用 亲测可用
  8. @Transactional 事务失效记录
  9. python自动测试g_python自动化测试报告(excel篇)
  10. JAVA Native Method 转自CSDN
  11. 【优化预测】基于matlab粒子群算法优化CNN预测【含Matlab源码 362期】
  12. 水晶易表 Xcelsius 2008 安装指南 完美支持office2010
  13. 移远4g LTE模块at指令集合
  14. [Mybatis]复杂环境下的SQL
  15. 连接到linux桌面,widows 远程连接到linux 桌面!
  16. dell r510服务器怎么装系统,DellR510安装系统.docx
  17. PDF文档用什么软件打开?
  18. Camtasia2023简体中文标准版免费更新下载
  19. [java] java语言基础
  20. (九十)第六章复习题

热门文章

  1. CCNA学习指南第十一章
  2. url的关键字不知道是uft-8还是GBK
  3. SVN忽略不必要的配置文件
  4. 构造器和析构器 - C++快速入门15
  5. RMS 相关下载链接
  6. ⼤海捞针 —— Scan
  7. 标准差、方差、协方差的区别
  8. 穷举 迭代 while
  9. java 解析并生成 XML
  10. ANDROID自定义视图——onMeasure流程,MeasureSpec详解