Servlet上传zip文件并解压

根据需要写一个上传文件的小程序,比较简单就用serlvet写。首先是要上传文件到服务器,然后是解压删除zip包。同时写一个监听器,用于进度条展现上传进度。


首先是页面Upload.jsp:前台需要上传一个文件和上传文件名称(对应服务器的相应目录),Ajax提交请求以实现进度条变化。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  



上传文件










   

        文件上传

       

           

           

               
             
             
           

       

       
                 
       
       

           




           
               

           


                
               
 
               
 
               
 
               
           

       



   




 



然后是文件上传的serlvet:UploadServletMy.java  request请求包含了文件类型的input和select下拉菜单,遍历判断顺序应该和jsp页面顺序对应,保证pathR的值

不为空。

package com.helloweenvsfei.servlet;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class UploadServletMy extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.getWriter().println("请以 POST 方式上传文件");
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

File file1 = null;
//String description1 = null;
String pathL ="E:/wz/webhomenew/mwr2016/zzsc/tjgb/";
/*String pathR = request.getParameter("username");
System.out.println("select:"+pathR);
String path =pathL+pathR;*/
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();

DiskFileItemFactory factory= new DiskFileItemFactory();

//临时文件暂存的路径
File tmpFile = new File(getServletContext().getRealPath("/WEB-INF/")+"/tmp");

if(!tmpFile.exists())
{
tmpFile.mkdir();
}
//缓存临时文件
factory.setRepository(tmpFile);
ServletFileUpload sfu= new ServletFileUpload(factory);
//文件上传进度的监听
UploadProgressListener listener=new UploadProgressListener(request);
sfu.setProgressListener(listener);
// 使用 DiskFileUpload 对象解析 request
// DiskFileUpload diskFileUpload = new DiskFileUpload();
try {
// 将 解析的结果 放置在 List 中
List list = sfu.parseRequest(request);
out.println("遍历所有的 FileItem ...
");
// 遍历 list 中所有的 FileItem
System.out.println("request请求信息数:"+list.size());;
for(FileItem fileItem : list){
if(fileItem.isFormField()){
// 如果是 文本域
pathR=new String(fileItem.getString().getBytes("iso8859-1"),"utf-8")+"/";
System.out.println("普通内容:"+fileItem.getFieldName()+"值为:"+pathR);
}
else{
// 否则,为文件域
if("file1".equals(fileItem.getFieldName())){
// 客户端文件路径构建的 File 对象
File remoteFile = new File(new String(fileItem.getName().getBytes(), "UTF-8"));
out.println("遍历到 file1 ...
"+new String(fileItem.getName().getBytes(), "UTF-8"));
// out.println("客户端文件位置: " + remoteFile.getAbsolutePath() + "
");
// 服务器端文件,放在 upload 文件夹下
System.out.println(remoteFile.getName());

/* Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
Matcher m = p.matcher(remoteFile.getName());
//判断上传文件名字是否包含中文
if(m.find()){
out.println("文件名称不符合规则");
out.println("返回上一页");
return;
} */
System.out.println("pathR:"+pathR);
file1 = new File("D:/temp/aaa/"+remoteFile.getName());
if(file1.exists()){
System.out.println("文件已存在,路径为:"+file1.getAbsolutePath());
out.println("文件已存在。");
out.println("返回上一页");
return;
}
file1.createNewFile();

System.out.println(file1.getAbsolutePath());
System.out.println(remoteFile.getName());
file1.getParentFile().mkdirs();
file1.createNewFile();

// 写文件,将 FileItem 的文件内容写到文件中
InputStream ins = fileItem.getInputStream();
FileOutputStream ous = new FileOutputStream(file1);
try{

byte[] buffer = new byte[1024];
int len = 0;
while((len=ins.read(buffer)) > -1){
ous.write(buffer, 0, len);
}
ous.close();
out.println("已保存文件" + file1.getAbsolutePath() + "
");
} finally{

ins.close();
}
}
}
}
out.println("Request 解析完毕");
} catch (Exception e) { //FileUploadException
// TODO Auto-generated catch block
e.printStackTrace();
e.getMessage();
}
HttpSession session=request.getSession();
session.setAttribute("file", file1);
session.setAttribute("pathR", pathR);
request.getRequestDispatcher("/servlet/FileUnzipServlet").forward(request,response);
out.flush();
out.close();

}

}

接着是解压zip的serlvet:FileUnzipServlet.java


package com.helloweenvsfei.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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 com.doczip.ZipDecompressing;


public class FileUnzipServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
       response.setCharacterEncoding("UTF-8");
       response.getWriter().println("请以 POST 方式上传文件");
   }


   @SuppressWarnings("unchecked")
   public void doPost(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
     
    response.setCharacterEncoding("UTF-8");
       response.setContentType("text/html");
       PrintWriter out = response.getWriter();
       HttpSession session=request.getSession();  
      File   file1 = (File) session.getAttribute("file");
      String pathR = (String) session.getAttribute("pathR");
 //上传后解压zip文件
        if(file1.getAbsolutePath().contains(".zip")){
        File zipFile = new File(file1.getAbsolutePath());  
        String pathZip = "D:/temp/aaa/"; 
        File pathFile = new File(pathZip);
        File temp = null;
        File[] filelist = pathFile.listFiles();
        String zipFileName = zipFile.getName();
        String prefix=zipFileName.substring(zipFileName.lastIndexOf("."));
        String checkname =zipFileName.substring(0, zipFileName.length()-prefix.length());
        System.out.println("名字名字"+checkname);
        
        out.println("");
        out.println("");
        out.println("  A Servlet");
        out.println("  ");
        out.println("  ");


        out.println("


");
        out.println("
上传文件
");


        out.println("      
");
        out.println("          
上传日志:
");
        out.println("          
");
        for (int i = 0; i < filelist.length; i++) {
            temp = filelist[i];
            System.out.println(temp.getName());
            if (temp.getName().equals(checkname)) {// 获得文件名,如果后缀为“”,checkname,就删除文件
            file1.delete();
            System.out.println("此文件已存在,请手动覆盖至服务器!");
            out.println(" 此文件已存在,请手动覆盖至服务器!");
            out.println("" + file1.getName() +  "文件链接地址");
            out.println("返回上一页");
               return ;
                        }
                          }
       //解压文件删除zip 
        ZipDecompressing.unZipFiles(zipFile, pathZip); 
        file1.delete();
       /* request.getRequestDispatcher("/result.jsp").forward(request, response);*/
        out.println("          
");
        out.println("      
");
        
        if(file1 != null){
        out.println("      
");
        out.println("          
file1:
");
        out.println("          
");
        out.println("               " + file1.getName() +  "文件链接地址"   );
        out.println("          
");
        out.println("      
");
        }
        out.println("      
");
        out.println("          
description1:
");
        out.println("          
");
        out.println("返回上一页");
        out.println("          
");
        out.println("      
");
        out.println("
");


        out.println("  ");
        out.println(""); }


}
}




package com.helloweenvsfei.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
* 文件上传进度状态类
* @author
*
*/

public class fileUploadStatusServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doPost(request,response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");

HttpSession session=request.getSession();

Object status = session.getAttribute("key");//获取上传进度百分比
if(status==null) return;
PrintWriter out = response.getWriter();
out.write(status.toString());
out.flush();
out.close();

}

}



package com.helloweenvsfei.servlet;  
  
import java.text.NumberFormat;  
  
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 kiloBytes=-1;  
      
    public UploadProgressListener(HttpServletRequest request) {  
          
        this.session = request.getSession();  
    }  
  
    //pBytes  
    public void update(long PBytesRead, long PContentLength, int PItems) {  
      
        Long KBytes=PBytesRead/1024;  
        if(kiloBytes==KBytes)  
        {  
            return;  
        }  
        kiloBytes=KBytes;  
        System.out.println("正在读取项目"+KBytes);  
        if(PContentLength==-1)  
        {  
            System.out.println("目前已经读取了"+PBytesRead+"字节数据");  
        }  
        else  
        {  
            System.out.println("目前已经读取了"+PContentLength+"中的"+PBytesRead+"字节数据");  
        }  
        //获取上传进度的百分比  
        double read=((double)KBytes)/(PContentLength/1024);  
          
          
        NumberFormat nf=NumberFormat.getPercentInstance();  
          
        session.setAttribute("key", nf.format(read));  
          
        System.out.println("进度时间:"+nf.format(read));  
          
    }  
}

你可能感兴趣的:(java学习,java,servlet,文件上传,解压缩)