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>

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

  1. PHP自动解压上传的rar文件

    PHP自动解压上传的rar文件   浏览:383 发布日期:2015/07/20 分类:功能实现 关键字: php函数 php扩展 大家都知道php有个zip类可直接操作zip压缩文件,可是用户有时候 ...

  2. php上传zip文件在线解压文件在指定目录下,CI框架版本

    我从网上找的文件php在线解压zip压缩文件 文件为jy.php可以直接执行,但是怎样将其加到CI框架中呢?? jy.php文件 <?php header("content-Type: ...

  3. 解压上传的zip文件流和文件

    /** * 解压上传的zip文件流 * @param stream * @param outputDirectory */ public static String unzip(InputStream ...

  4. Flask保存或解压上传的文件

    import os import uuid import shutil import zipfile from flask import Flask, render_template, request ...

  5. 《手把手教你》系列技巧篇(五十五)-java+ selenium自动化测试-上传文件-下篇(详细教程)

    1.简介 在实际工作中,我们进行web自动化的时候,文件上传是很常见的操作,例如上传用户头像,上传身份证信息等.所以宏哥打算按上传文件的分类对其进行一下讲解和分享. 2.为什么selenium没有提供 ...

  6. java多图片上传--前端实现预览--图片压缩 、图片缩放,区域裁剪,水印,旋转,保持比例。

    java多图片上传--前端实现预览 前端代码: https://pan.baidu.com/s/1cqKbmjBSXOhFX4HR1XGkyQ 解压后: java后台: <!--文件上传--&g ...

  7. JAVA 实现FTP上传下载(sun.net.ftp.FtpClient)

    package com.why.ftp; import java.io.DataInputStream; import java.io.File; import java.io.FileInputSt ...

  8. Delphi调用JAVA的WebService上传XML文件(XE10.2+WIN764)

    相关资料:1.http://blog.csdn.net/luojianfeng/article/details/512198902.http://blog.csdn.net/avsuper/artic ...

  9. Java 利用FTP上传,下载文件,遍历文件目录

    Java实现FTP上传下载文件的工具包有很多,这里我采用Java自带的API,实现FTP上传下载文件.另外JDK1.7以前的版本与其之后版本的API有了较大的改变了. 例如: JDK1.7之前 JDK ...

随机推荐

  1. yii2怎样写规则可以隐藏url地址里的控制器名字

    yii2怎样写规则可以隐藏url地址里的控制器名字,例如现在的是***.com/site/index.html要变成***.com/index.html '<action:index>.h ...

  2. EntityFramework中的datetime2异常的解决

    (转)   最近使用.net的Entity Framework构建网站数据层,给一个实体的DATETIME类型的属性赋值时 突然莫名奇妙显示有一个类型不匹配的异常如下: System.Data.Sql ...

  3. iOS性能调优之Analyze静态分析

    之前遇到一个同事写的 陈年老工程,需要尽快的时间修改里面的东西,急用,让我帮忙.那就帮着看看. 而Analyze这个工具 真是好用. 工程存在严重的内存泄漏.  如果不解决  很容易就会出现崩溃等现象 ...

  4. 微信小程序、应用号、订阅号、服务号、企业号小总结

    微信小程序是现在微信推出的一个新的项目,但是很多人都不是很清楚微信小程序是怎么一回事,不明白到底怎样分别微信小程序和别的公众号.订阅号等的区别,那么让小编来给你介绍一下. 微信小程序目前是内侧阶段,是 ...

  5. 在云服务器搭建WordPress博客(五)创建和管理文章分类

    不同主题的文章划分到不同的分类,有助于访客寻找他们想要的内容,提高用户体验.所以,为你的网站创建文章分类是很有必要的.那么,WordPress系统如何创建和管理文章分类呢?今天倡萌就简单介绍一下. 创 ...

  6. 在云服务器搭建WordPress博客(四)WordPress的基本设置

    前面说了 如何安装WordPress,接下来我们需要快速熟悉WordPress,以及进行一些必要的基本设置. 开始设置之前,建议大家先点击一篇左边菜单栏的每一个选项,看看到底是做什么用的.下面开始说一 ...

  7. myeclipse/eclipse添加Spket插件实现ExtJs4.2/ExtJs3智能提示

    前言 感谢luotao,本博客是copy这篇博客的:http://www.cnblogs.com/luotaoyeah/p/3803926.html ,因为太重要了,所以笔者再写一次. 重要说明:ec ...

  8. Unity3d 接入 移动MM支付SDK(2.3) 全攻略

    原地址:http://blog.csdn.net/dingxiaowei2013/article/details/26842177 先将例程运行起来 下载例程(csdn积分不够上传不了,只能用百度网盘 ...

  9. 设置go语言语法高亮

    1. 将$GOROOT/misc/vim/go.vim文件拷贝到-/.vim/syntax/目录下 2. 添加下面代码到~/.vimrc文件中 let mysyntaxfile = "XXX ...

  10. lua语言入门之Sublime Text设置lua的Build System

    转自: http://blog.csdn.net/wangbin_jxust/article/details/8911956 最近开始学习LUA语言,使用Sublime Text作为编辑器,不得不说, ...