1. 程式人生 > >Servlet上傳zip檔案並解壓

Servlet上傳zip檔案並解壓

根據需要寫一個上傳檔案的小程式,比較簡單就用serlvet寫。首先是要上傳檔案到伺服器,然後是解壓刪除zip包。同時寫一個監聽器,用於進度條展現上傳進度。

首先是頁面Upload.jsp:前臺需要上傳一個檔案和上傳檔名稱(對應伺服器的相應目錄),Ajax提交請求以實現進度條變化。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>上傳檔案</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="./js/jquery-1.11.1.min.js" type="text/javascript"></script>


</head>
<body>
<form action="servlet/UploadServletMy"  method="post" id="form" enctype="multipart/form-data">
<div align="center">
    <fieldset style="width:80%">
        <legend>檔案上傳</legend><br/>
        <div class='line'>
            <div align='left' ></div>
            <div align='left' >
             <select name="select" id="select_k1" class="xla_k">
             <option value="tjgb">統計公報</option>
             <option value="dycqgslpcgb">第一次全國水利普查公報</option>
             <option value="slfztjgb">水利發展統計公報</option>
             <option value="szygb">水資源公報</option>
             <option value="zghlnsgb">中國河流泥沙公報</option>
             <option value="slkjcggb">水利科技成果公報</option>
             <option value="zgshzhgb">中國水旱災害公報</option>
             <option value="zgstbcgb">中國水土保持公報</option>
             <option value="swxytjnb">水文行業統計年報</option>
             <option value="sqnb">水情年報</option>
             <option value="dxsdtyb">地下水動態月報</option>
             <option value="zysljstztjyb">中央水利建設投資統計月報</option>
             <option value="xxbxskcxjgtb">小型病險水庫除險加固通報</option>
             <option value="ncsdnb">農村水電年報</option>
             </select>  
             <input type="file" name="file1" id="file1" value=""></input>
             
            </div>
        </div>
        <!--  <input type="text" name="username" id="username" class="text" /> -->
                 
        <!--  <div class='line'>
            <div align='left' class="leftDiv">檔案說明(文字域)</div>
            <div align='left' class="rightDiv"><input type="text" name="description1" value="description1"/></div>
        </div> -->
        <div class='line'>
            <div align='left' ><br/><br/><br/>
            <input type="button" value="點選上傳"  onclick="formSubmit();" />
                </div>
            <div align='left' ><br/>
                
                <div style="width:300px;">  
                <div id="show" style="background:#ADFF2F;height:26px;width:0%;"></div>  
                </div>  
                <span id="msg"></span>
            </div>
        </div>


    </fieldset>
</div>


</form>  
</body>
<script language="javascript">
  var progress;  
  var uploadProcessTimer = null;  
function getFileUploadProcess() {   
              $.ajax({  
                     type:"POST",  
                     url:"servlet/fileUploadStatusServlet",  
                     dataType:"text",  
                     cache:false,  
                     success:function(data){ 
                              
                         if(data=="100%"){  
                             window.clearInterval(uploadProcessTimer);  
                         }else{  
                              progress=data;  
                             $("#show").width(data);  
                             $("#msg").text(data);  
                         }  
                     }  
             });  
          };             
function formSubmit(){  


var str;
str=$('#file1').val();
var arr=str.split("\\");//注split可以用字元或字串分割
var my=arr[arr.length-1];//這就是要取得的圖片名稱
var reg = new RegExp("[\\u4E00-\\u9FFF]+","g");
if(reg.test(arr)){
   alert("上傳檔案包含中文名字,請修正後上傳!");
   return;
}else{
   /*  var act="servlet/UploadServletMy";     
    url =act+"?username="+document.getElementById("select_k1").value; 
    $('form').attr('action',url);      */     
    $("form").submit();  
    timer=self.setInterval("getFileUploadProcess()",10);
  }
}  
</script>
</html>

然後是檔案上傳的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<FileItem> list = sfu.parseRequest(request);
out.println("遍歷所有的 FileItem ... <br/>");
// 遍歷 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 ... <br/>"+new String(fileItem.getName().getBytes(), "UTF-8"));
// out.println("客戶端檔案位置: " + remoteFile.getAbsolutePath() + "<br/>");
// 伺服器端檔案,放在 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("<a href='javascript:'onclick='self.location=document.referrer;'>返回上一頁</a>");
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("<a href='javascript:'onclick='self.location=document.referrer;'>返回上一頁</a>");
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() + "<br/>");
} 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("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <link rel='stylesheet' type='text/css' href='../css/style.css'>");
        out.println("  <BODY>");


        out.println("<div align=center><br/>");
        out.println("<fieldset style='width:90%'><legend>上傳檔案</legend><br/>");


        out.println("       <div class='line'>");
        out.println("           <div align='left' class='leftDiv'>上傳日誌:</div>");
        out.println("           <div align='left' class='rightDiv'>");
        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("<a href='http://www.mwr.gov.cn/zzsc/tjgb/" + pathR +"/"+ checkname + "' target=_blank>" + file1.getName() +  "檔案連結地址</a>");
            out.println("<a href='javascript:'onclick='self.location=document.referrer;'>返回上一頁</a>");
               return ;
                        }
                          }
       //解壓檔案刪除zip 
        ZipDecompressing.unZipFiles(zipFile, pathZip); 
        file1.delete();
       /* request.getRequestDispatcher("/result.jsp").forward(request, response);*/
        out.println("           </div>");
        out.println("       </div>");
        
        if(file1 != null){
        out.println("       <div class='line'>");
        out.println("           <div align='left' class='leftDiv'>file1:</div>");
        out.println("           <div align='left' class='rightDiv'>");
        out.println("               <a href='http://www.mwr.gov.cn/zzsc/tjgb/" + pathR +"/"+ checkname + "' target=_blank>" + file1.getName() +  "檔案連結地址</a>"   );
        out.println("           </div>");
        out.println("       </div>");
        }
        out.println("       <div class='line'>");
        out.println("           <div align='left' class='leftDiv'>description1:</div>");
        out.println("           <div align='left' class='rightDiv'>");
        out.println("<a href='javascript:'onclick='self.location=document.referrer;'>返回上一頁</a>");
        out.println("           </div>");
        out.println("       </div>");
        out.println("</fieldset></div>");


        out.println("  </BODY>");
        out.println("</HTML>"); }


}
}


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));  
          
    }  
}