package com.zip;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
public class AntZip {
/**
* @param sourcefiles 源文件或者目录
* @param compfilepath 压缩文件路径
* @throws IOException IO异常
*/
public boolean zip(String sourcefiles, String compfilepath) throws IOException {
boolean succflag=false;
if(sourcefiles.equals("") || compfilepath.equals(""))
return succflag; //如果源文件或目标文件为空,则返回0
ZipOutputStream out = null;
try
{
File compfile =new File(compfilepath);
out = new ZipOutputStream(compfile);
File fileOrDirectory =new File(sourcefiles);
if (fileOrDirectory.isFile())
zipFileOrDirectory(out, fileOrDirectory, "");
else {
File[] entries = fileOrDirectory.listFiles();
for (int i = 0; i < entries.length; i++)
// 递归压缩
{
zipFileOrDirectory(out, entries[i], "");
}
}
succflag=true;
compfile=null;
fileOrDirectory=null;
} catch (IOException ex) {
succflag=false;
ex.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException ex) {
}
}
out=null;
}
return succflag;
}
/**
* @param out 压缩输出流对象
* @param compresobject 要压缩的文件或目录对象
* @param curPath 当前压缩条目的路径,用于指定条目名称的前缀
* @throws IOException IO异常
*/
private boolean zipFileOrDirectory(ZipOutputStream out,File compresobject,String curPath) throws IOException {
boolean succflag=false;
FileInputStream in = null;
try
{
if (!compresobject.isDirectory())
{
// 压缩文件
byte[] buffer = new byte[4096];
int bytes_read;
in = new FileInputStream(compresobject);
ZipEntry entry =new ZipEntry(curPath + compresobject.getName());
out.putNextEntry(entry);
while ((bytes_read = in.read(buffer)) != -1)
{
out.write(buffer, 0, bytes_read);
}
out.closeEntry();
} else
{
// 压缩目录
File[] entries = compresobject.listFiles();
for (int i = 0; i < entries.length; i++) {
// 递归压缩,更新curPaths
zipFileOrDirectory(out,entries[i],curPath + compresobject.getName() + "/");
}
}
succflag=true;
} catch (IOException ex) {
succflag=false;
ex.printStackTrace();
throw ex;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
succflag=false;
ex.printStackTrace();
}
}
in=null;
}
return succflag;
}
/**
* @param sourcefiles 源文件
* @param decompreDirectory 解压缩后文件存放的目录
* @throws IOException IO异常
*/
@SuppressWarnings("unchecked")
public static void unzip(String sourcefiles, String decompreDirectory) throws IOException {
ZipFile readfile = null;
try {
readfile =new ZipFile(sourcefiles);
Enumeration takeentrie = readfile.getEntries();
ZipEntry zipEntry = null;
File credirectory = new File(decompreDirectory);
credirectory.mkdirs();
while (takeentrie.hasMoreElements()) {
zipEntry = (ZipEntry) takeentrie.nextElement();
String entryName = zipEntry.getName();
InputStream in = null;
FileOutputStream out = null;
try {
if (zipEntry.isDirectory()) {
String name = zipEntry.getName();
name = name.substring(0, name.length() - 1);
File createDirectory = new File(decompreDirectory+ File.separator + name);
createDirectory.mkdirs();
} else {
int index = entryName.lastIndexOf("\\");
if (index != -1) {
File createDirectory = new File(decompreDirectory+ File.separator+ entryName.substring(0, index));
createDirectory.mkdirs();
}
index = entryName.lastIndexOf("/");
if (index != -1) {
File createDirectory = new File(decompreDirectory + File.separator + entryName.substring(0, index));
createDirectory.mkdirs();
}
File unpackfile = new File(decompreDirectory + File.separator + zipEntry.getName());
in = readfile.getInputStream(zipEntry);
out = new FileOutputStream(unpackfile);
int c;
byte[] by = new byte[1024];
while ((c = in.read(by)) != -1) {
out.write(by, 0, c);
}
out.flush();
}
} catch (IOException ex) {
ex.printStackTrace();
throw new IOException("解压失败:" + ex.toString());
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
in=null;
out=null;
}
}
} catch (IOException ex) {
ex.printStackTrace();
throw new IOException("解压失败:" + ex.toString());
} finally {
if (readfile != null) {
try {
readfile.close();
} catch (IOException ex) {
ex.printStackTrace();
throw new IOException("解压失败:" + ex.toString());
}
}
}
}
}
2
package com.zip;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;
import de.innosystec.unrar.Archive;
import de.innosystec.unrar.rarfile.FileHeader;
public class DeCompressUtil {
/**
* 解压zip格式压缩包
* 对应的是ant.jar
*/
private static void unzip(String sourceZip,String destDir) throws Exception{
try{
Project p = new Project();
Expand e = new Expand();
e.setProject(p);
e.setSrc(new File(sourceZip));
e.setOverwrite(false);
e.setDest(new File(destDir));
/*
ant下的zip工具默认压缩编码为UTF-8编码,
而winRAR软件压缩是用的windows默认的GBK或者GB2312编码
所以解压缩时要制定编码格式
*/
e.setEncoding("gbk");
e.execute();
}catch(Exception e){
throw e;
}
}
/**
* 解压rar格式压缩包。
* 对应的是java-unrar-0.3.jar,但是java-unrar-0.3.jar又会用到commons-logging-1.1.1.jar
*/
private static void unrar(String sourceRar,String destDir) throws Exception{
Archive a = null;
FileOutputStream fos = null;
try{
a = new Archive(new File(sourceRar));
FileHeader fh = a.nextFileHeader();
while(fh!=null){
if(!fh.isDirectory()){
//1 根据不同的操作系统拿到相应的 destDirName 和 destFileName
String compressFileName = fh.getFileNameString().trim();
String destFileName = "";
String destDirName = "";
//非windows系统
if(File.separator.equals("/")){
destFileName = destDir + compressFileName.replaceAll("\\\\", "/");
destDirName = destFileName.substring(0, destFileName.lastIndexOf("/"));
//windows系统
}else{
destFileName = destDir + compressFileName.replaceAll("/", "\\\\");
destDirName = destFileName.substring(0, destFileName.lastIndexOf("\\"));
}
//2创建文件夹
File dir = new File(destDirName);
if(!dir.exists()||!dir.isDirectory()){
dir.mkdirs();
}
//3解压缩文件
fos = new FileOutputStream(new File(destFileName));
a.extractFile(fh, fos);
fos.close();
fos = null;
}
fh = a.nextFileHeader();
}
a.close();
a = null;
}catch(Exception e){
throw e;
}finally{
if(fos!=null){
try{fos.close();fos=null;}catch(Exception e){e.printStackTrace();}
}
if(a!=null){
try{a.close();a=null;}catch(Exception e){e.printStackTrace();}
}
}
}
/**
* 解压缩
*/
public static void deCompress(String sourceFile,String destDir) throws Exception{
//保证文件夹路径最后是"/"或者"\"
char lastChar = destDir.charAt(destDir.length()-1);
if(lastChar!='/'&&lastChar!='\\'){
destDir += File.separator;
}
//根据类型,进行相应的解压缩
String type = sourceFile.substring(sourceFile.lastIndexOf(".")+1);
if(type.equals("zip")){
DeCompressUtil.unzip(sourceFile, destDir);
}else if(type.equals("rar")){
DeCompressUtil.unrar(sourceFile, destDir);
}else{
throw new Exception("只支持zip和rar格式的压缩包!");
}
}
}
3。
package com.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.google.gson.Gson;
import com.zip.DeCompressUtil;
public class UploadFile extends HttpServlet {
private static final long serialVersionUID = 1L;
private String uploadpath = "upload";// 文件上传地址
private String unpackpath = "";
private long maxSize = 100 * 1024 * 1024;// 最大文件大小100M
private String limitfile = "zip,rar";// 限制上传类型doc,docx,xls,xlsx,ppt,htm,html,txt,
private Gson gson = new Gson();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
try {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html; charset=UTF-8");
String upid = req.getParameter("upid");
UploadState state = (UploadState) req.getSession().getAttribute("upstate");
String s="";
if (upid!=null&&state != null && upid.equals(state.getId())) {
s = gson.toJson(state);
}
System.out.println(state+" GET:"+upid+"_"+s);
PrintWriter out = resp.getWriter();
out.write(s);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
try {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html; charset=UTF-8");
String s="";
PrintWriter out = resp.getWriter();
boolean ismulti=ServletFileUpload.isMultipartContent(req);
if(ismulti){
HttpSession session=req.getSession();
UploadState us=(UploadState)session.getAttribute("upstate");
if (us == null) {
us = new UploadState();
session.setAttribute("upstate", us);
}
us.setTargetfile("");
us.setErrormsg("");
us.setTotalsize(0);
us.setUploadsize(0);
us.setState(0);// 默认正常状态
long length = req.getContentLength();
us.setTotalsize(length);
if (length > maxSize) {
setStatusMsg(req, -1, "文件内容超过最大限制!");
s = gson.toJson(us);
} else {
processFileUpload(req, out);
s = gson.toJson(us);
}
}
out.write(s);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public void processFileUpload(HttpServletRequest request, PrintWriter out)
throws ServletException, IOException {
String savePath=this.getServletConfig().getServletContext().getRealPath("/")+uploadpath;
// 临时文件目录
String tempPath = savePath + "/temp";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
String ymd = sdf.format(new Date());
String path = savePath + "/" + ymd + "/";
// 创建文件夹
File dirFile = new File(path);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
// 创建临时文件夹
File dirTempFile = new File(tempPath);
if (!dirTempFile.exists()) {
dirTempFile.mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(5 * 1024 * 1024); // 设定使用内存超过5M时,将产生临时文件并存储于临时目录中。
factory.setRepository(new File(tempPath)); // 设定存储临时文件的目录。
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
// 创建一个进度监听器
UploadProgressListener progressListener = new UploadProgressListener(
request);
upload.setProgressListener(progressListener);
upload.setFileSizeMax(maxSize);
try {
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
//如果是普通表单字段
String name = item.getFieldName();
if(name!=null&&name.equals("unpkpath")){
unpackpath = item.getString().trim();
}
}else{
String fileName = item.getName();
long fileSize = item.getSize();
// 检查文件大小
if (fileSize > maxSize) {
setStatusMsg(request, -1, "文件内容超过最大限制!");
break;
}
// 检查扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if (limitfile.indexOf(fileExt) < 0) {
setStatusMsg(request, -1, "上传文件扩展名是不允许的扩展名。只允许"
+ limitfile + "格式。!");
return;
}
String newFileName = System.currentTimeMillis() + "_"
+ new Random().nextInt(1000) + "." + fileExt;
File uploadedFile = new File(path, newFileName);
try {
HttpSession session = request.getSession();
UploadState state = (UploadState) session
.getAttribute("upstate");
state.setTargetfile(uploadedFile.getPath());
OutputStream os = new FileOutputStream(uploadedFile);
InputStream is = item.getInputStream();
byte buf[] = new byte[1024];// 可以修改 1024 以提高读取速度
int length = 0;
while ((length = is.read(buf)) > 0) {
os.write(buf, 0, length);
}
// 关闭流
os.flush();
os.close();
is.close();
} catch (Exception e) {
setStatusMsg(request, -1, "上传失败!");
return;
}
setStatusMsg(request, 1, "上传成功");
String unpath=this.getServletConfig().getServletContext().getRealPath("/")+unpackpath;
File f=new File(unpath);
if(!f.exists()){
f.mkdirs();
}
try {
DeCompressUtil.deCompress(uploadedFile.getPath(), unpath);
} catch (Exception e) {
e.printStackTrace();
}
// AntZip.unzip(uploadedFile.getPath(), unpath);//解压
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
private void setStatusMsg(HttpServletRequest request, int error,
String message) {
HttpSession session = request.getSession();
UploadState state = (UploadState) session.getAttribute("upstate");
state.setState(error);
state.setErrormsg(message);
}
}
4.
package com.servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.ProgressListener;
public class UploadProgressListener implements ProgressListener {
private HttpSession session;
// private long megaBytes = -1;
// private long maxSize = 100 * 1024 * 1024;// 最大文件大小100M
public UploadProgressListener(HttpServletRequest request) {
session = request.getSession();
UploadState us=(UploadState)session.getAttribute("upstate");
if (us == null) {
us = new UploadState();
session.setAttribute("upstate", us);
}
us.setState(0);// 默认正常状态
us.setTotalsize(0);
us.setId(request.getParameter("upid"));
}
/**
*
* 为了进度条监听器不会引起性能问题 解决方案,是减少进步条的活动数 比如,只有当上传了1兆字节的时候才反馈给用户
*
*/
public void update(long pBytesRead, long pContentLength, int pItems) {
/*
* long mBytes = pBytesRead / 1048576; if (megaBytes == mBytes) {
* return; } megaBytes = mBytes;
*/
UploadState state = (UploadState) session.getAttribute("upstate");
state.setTotalsize(pContentLength);
if (pContentLength == -1) {
state.setErrormsg("已完成" + pItems + "个文件的上传");
state.setState(1);
state.setUploadsize(pBytesRead);
} else {
state.setErrormsg("正在上传第" + pItems + "个文件");
state.setState(0);
state.setUploadsize(pBytesRead);
}
}
}
5.
package com.servlet;
public class UploadState {
private String id;//上传编号
private int state;//上传状态 0 正常 -1 错误 1 上传完毕
private String errormsg;//错误信息
private String targetfile;//目标文件
private long totalsize;//文件总大小
private long uploadsize;//已上传大小
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTargetfile() {
return targetfile;
}
public void setTargetfile(String targetfile) {
this.targetfile = targetfile;
}
/**
* 上传状态 0 正常 -1 错误 1 上传完毕
* @param state
*/
public int getState() {
return state;
}
/**
* 上传状态 0 正常 -1 错误 1 上传完毕
* @param state
*/
public void setState(int state) {
this.state = state;
}
public String getErrormsg() {
return errormsg;
}
public void setErrormsg(String errormsg) {
this.errormsg = errormsg;
}
public long getTotalsize() {
return totalsize;
}
public void setTotalsize(long totalsize) {
this.totalsize = totalsize;
}
public long getUploadsize() {
return uploadsize;
}
public void setUploadsize(long uploadsize) {
this.uploadsize = uploadsize;
}
}
6.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>