AJAX函數實現文檔的上傳壓縮下載

文檔上傳的一個簡單界面 docUpload.jsp:javascript

[java]  view plain copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'docUpload.jsp' starting page</title>  
  13.       
  14.     <meta http-equiv="pragma" content="no-cache">  
  15.     <meta http-equiv="cache-control" content="no-cache">  
  16.     <meta http-equiv="expires" content="0">      
  17.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  18.     <meta http-equiv="description" content="This is my page">  
  19.     <!--  
  20.     <link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">  
  21.     -->  
  22.       
  23.     <mce:script type="text/javascript" src="resources/jquery.js" mce_src="resources/jquery.js"></mce:script>   
  24.     <mce:script type="text/javascript" src="resources/upload/fileUploadUtil.js" mce_src="resources/upload/fileUploadUtil.js"></mce:script>  
  25.     <mce:script type="text/javascript" src="resources/ajaxfileupload.js" mce_src="resources/ajaxfileupload.js"></mce:script>   
  26.       
  27.   </head>  
  28.     
  29.     <mce:script type="text/javascript"><!--  
  30.            
  31.          //默認設置上傳文件的大小100M  
  32.          var uploadFileSize = "100000000";  
  33.            
  34.          $(document).ready(function(){  
  35.              $("#test").click(function(){  
  36.                  uploadFile();  
  37.              });  
  38.          });  
  39.       
  40. // --></mce:script>  
  41.     
  42.   <body>  
  43.          <form action="#">  
  44.            <table id="upload" border="1">  
  45.                <tr>  
  46.                   <td width="20%">序號</td>  
  47.                   <td width="30%">名字</td>  
  48.                   <td width="50%">路徑</td>  
  49.                   <td width="20%">狀態</td>  
  50.                </tr>  
  51.                <tr>  
  52.                   <td>1</td>  
  53.                   <td>111</td>  
  54.                   <td><input type="file" name="newfile" onchange="checkFile(this);"></input></td>  
  55.                   <td><p id="flag1">正常</p></td>  
  56.                </tr>  
  57.            </table>   
  58.              
  59.            <input type="submit" value="肯定" id="test"></input>  
  60.           </form>    
  61.   </body>  
  62. </html>  


2.  fileUploadUtil.js 爲上傳下載文檔都須要引入的JScss

[javascript]  view plain copy
  1. /** 
  2.  *  定義全局變量 
  3.  */  
  4. var uploadFileSize = ""// 定義文檔內容的大小  
  5. var checkFileFlag = false//文件是否已經檢查的標誌  
  6. var fileCount = -1;   
  7. var paramterUrl = ""//定義傳遞到後臺的參數  
  8.   
  9.   
  10. function uploadFile() {  
  11.      
  12.      //對上傳框內的內容進行判斷  
  13.      if(checkFileFlag == false) {  
  14.           checkFileFlag = true;  
  15.           var flag = checkFilePath();  
  16.           if(flag) {  
  17.               alert("/u6587/u4ef6/u5730/u5740/u4e0d/u80fd/u4e3a/u7a7a!");  
  18.               checkFileFlag = false;  
  19.               return;  
  20.           }   
  21.      }  
  22.        
  23.      fileCount++;  
  24.      var fileId = "";  
  25.      var filePath = "";  
  26.        
  27.      //這邊是每次都對對應的須要上傳的文檔進行過濾  
  28.      $(":file[id*='uploadFileName']").each(function(i){  
  29.           if(i == fileCount) {  
  30.               fileId = $(this).attr("id");  
  31.               filePath = $(this).val();  
  32.           }  
  33.      });  
  34.        
  35.      if(filePath == null || filePath == "") {  
  36.          return;   
  37.      } else {  
  38.          $("p[id*='showName']").each(function(i){  
  39.                if(i == fileCount) {  
  40.                    $(this).text("/u6587/u4ef6/u4e0a/u4f20/u4e2d/u3002/u3002/u3002/u3002/u3002");  
  41.                    $("#test").attr("disabled","disabled");  
  42.                    //後面執行上傳文件的動做,調用後臺的Servlet  
  43.                    doUploadFile(filePath,fileId);  
  44.                }  
  45.          });  
  46.      }  
  47. }  
  48.   
  49.   
  50. /** 
  51.  * 執行上傳文件的動做 
  52.  */  
  53. function doUploadFile(filePath,fileId) {  
  54.       
  55.     //得到上傳文件的文件名  
  56.     var paths = filePath.split("//");  
  57.     var fileName = paths[paths.length - 1];  
  58.       
  59.     //定義傳遞到後臺的參數  
  60.     //paramterUrl = "name=lin&age=20";  
  61.   
  62.     var url = "/AJAX/servlet/FileUploadServlet?" + "name=linwei1111";   
  63.     url = encodeURI(encodeURI(url));  
  64.       
  65.     //下面開始調用Servlet傳遞文件流到後臺,下面是在ajaxfileupload.js文件中的,,就已經有enctype設置了。  
  66.     //var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');     
  67.     $.ajaxFileUpload({       
  68.         type:"POST",  
  69.         secureuri:false,  
  70.         //**文件上傳空間的id屬性,這邊須要寫入對應的上傳文件的fileId  
  71.         fileElementId:fileId,  
  72.         dataType:"json",  
  73.         url: url,  
  74.         //data:{name:'linwei',age:'20'},  
  75.         success:function(data){  
  76.             if(data.status == "success") {  
  77.                      $("p[id*='showName']").each(function(i){  
  78.                            if(i == fileCount) {  
  79.                            $(this).text("/u4e0a/u4f20/u6210/u529f");  
  80.                       }  
  81.                      });  
  82.              } else {  
  83.                  $("p[id*='showName']").each(function(i){  
  84.                            if(i == fileCount) {  
  85.                            $(this).text("/u4e0a/u4f20/u5931/u8d25");  
  86.                       }  
  87.                  });  
  88.              }  
  89.              gotoNextUpload();  
  90.         },  
  91.         error:function(xhr,status,err) {  
  92.              alert("/u51fa/u9519/u4e86/u3002");  
  93.              gotoNextUpload();  
  94.         }  
  95.     });  
  96. }  
  97.   
  98.   
  99. /**  
  100.  * 跳轉到下一個頁面,判斷是否繼續上傳文檔  
  101.  */  
  102. function gotoNextUpload() {  
  103.      //獲取上傳文檔的數量  
  104.      var size = $(":file[id*='uploadFileName']").size();  
  105.        
  106.      if(fileCount<size-1) {  
  107.           uploadFile();       
  108.      } else {  
  109.           $("#test").removeAttr("disabled");  
  110.      }  
  111. }  
  112.   
  113.   
  114. /** 
  115.  * 檢查文檔路徑是否爲空 
  116.  */  
  117. function checkFilePath() {  
  118.       
  119.     var flag = false;  
  120.     $("input[name*='a']").each(function(i){  
  121.          if($(this).val() == null || $(this).val() == "") {  
  122.               flag = true;   
  123.               return flag;  
  124.          }  
  125.     });   
  126.     return flag;   
  127. }  
  128.   
  129. /** 
  130.  * 文檔上傳以前,對上傳的文檔內容進行檢查。(檢查內容包括:文檔後綴,文檔大小等) 
  131.  */  
  132. function checkFile(obj) {  
  133.       
  134.     //根據文檔路徑是否存在進行判斷  
  135.     if(obj.value.length>0) {  
  136.         //定義能夠上傳的文檔類型  
  137.         var af = "jpg,gif,png,zip,rar,txt,doc,htm,pdf,xls";  
  138.           
  139.         if (eval("with(obj.value)if(!/" + af.split(",").join("|")  
  140.                 + "/ig.test(substring(lastIndexOf('.')+1,length)))1;")) {  
  141.                   
  142.             alert("/u5141/u8bb8/u4e0a/u4f20/u7684/u6587/u6863/u7c7b/u578b/u4e3a:/n" + af);  
  143.             //清楚文件上傳框中的內容  
  144.             obj.outerHTML = obj.outerHTML;  
  145.         } else {  
  146.             checkFileSize(obj);  
  147.         }  
  148.     }  
  149. }  
  150.   
  151. /** 
  152.  * 檢查文檔內容的大小 
  153.  */  
  154. function checkFileSize(obj) {  
  155.        
  156.      if (!getFileSize(obj.value)) {  
  157.          obj.outerHTML = obj.outerHTML;  
  158.          alert("/u4e0a/u4f20/u6587/u4ef6/u5927/u5c0f/u8bf7/u52ff/u5927/u4e8e"+parseInt(Number(uploadFileSize)/(1000*1000))+"M");  
  159.      }  
  160. }  
  161.   
  162. /** 
  163.  * 取得上傳文檔的大小 
  164.  */  
  165. function getFileSize(filePath) {  
  166.        
  167.      var fileSize = "-1";  
  168.   
  169.      //經過Img對象裝載,這個能夠是能夠,可是瀏覽器有嚴格限制,如今最主流的瀏覽器都是ie內核的,  
  170.      //ie7和ie8的在裝載Img對象是用dynsrc裝載不了,只有ie6能夠,這可能跟內核有關係。   
  171.      var image = new Image();  
  172.      image.dynsrc = filePath;  
  173.      fileSize = image.fileSize;  
  174.        
  175.      //另一種方式獲取文件大小的  
  176.      //var fso,f;    
  177.      //fso=new ActiveXObject("Scripting.FileSystemObject");    
  178.      //f=fso.GetFile(filePath);  
  179.      //var fileSize = f.size ;  
  180.        
  181.      if(Number(fileSize)<Number(uploadFileSize)) {  
  182.          return true;  
  183.      } else {  
  184.          return false;  
  185.      }  
  186. }  
  187.   
  188. //=============================================================  
  189. /** 
  190.  * 頁面載入後先執行的動做 
  191.  */  
  192.   
  193. $(document).ready(function(){  
  194.       
  195.     //對頁面的文件進行ID的編排  
  196.     $(":file").each(function(i){  
  197.         var thisFileId = i + "uploadFileName";  
  198.         //alert("a is " + thisFileId);  
  199.         $(this).attr("id",thisFileId);  
  200.     });  
  201.       
  202.     //對頁面的顯示內容進行ID的編排  
  203.     $("p[id*='flag']").each(function(i){  
  204.         var thisShowId = i + "showName";  
  205.         //alert("b is " + thisShowId);  
  206.         $(this).attr("id",thisShowId);  
  207.     });  
  208.       
  209.       
  210.       
  211. });  
  212.   
  213.   
  214. //=============================================================  
  215. //頁面調用文檔函數  
  216. function doFileDown(id) {  
  217.        
  218.      var url = "http://localhost:8080/AJAX/servlet/fileDownload?id=" + id;  
  219.      $("#" + id).attr("href",url);  
  220.      $("#" + id).click(function(){  
  221.          alert($(this).attr("href"));  
  222.      });  
  223.        
  224. }  

 

 

 3.   FileUploadServlet.java 是上傳的Servlethtml

 

  

[java]  view plain copy
  1. package upload;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5. import java.util.HashMap;  
  6. import java.util.Map;  
  7.   
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.http.HttpServlet;  
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12.   
  13. import org.apache.commons.fileupload.FileUploadException;  
  14.   
  15. import service.JsonUtil;  
  16.   
  17. public class FileUploadServlet extends HttpServlet {  
  18.       
  19.     Map map = new HashMap();  
  20.   
  21.     /** 
  22.      * Constructor of the object. 
  23.      */  
  24.     public FileUploadServlet() {  
  25.         super();  
  26.     }  
  27.   
  28.     /** 
  29.      * Destruction of the servlet. <br> 
  30.      */  
  31.     public void destroy() {  
  32.         super.destroy(); // Just puts "destroy" string in log  
  33.         // Put your code here  
  34.     }  
  35.   
  36.     /** 
  37.      * The doGet method of the servlet. <br> 
  38.      *  
  39.      * This method is called when a form has its tag value method equals to get. 
  40.      *  
  41.      * @param request 
  42.      *            the request send by the client to the server 
  43.      * @param response 
  44.      *            the response send by the server to the client 
  45.      * @throws ServletException 
  46.      *             if an error occurred 
  47.      * @throws IOException 
  48.      *             if an error occurred 
  49.      */  
  50.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  51.             throws ServletException, IOException {  
  52.   
  53.         System.out.println("in doGet.");  
  54.    
  55.         response.setContentType("text/html; charset=UTF-8");  
  56.         PrintWriter out = response.getWriter();  
  57.         out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">");  
  58.         out.println("<HTML>");  
  59.         out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");  
  60.         out.println("  <BODY>");  
  61.         out.print("    This is ");  
  62.         out.print(this.getClass());  
  63.         out.println("in doGet method, using the GET method");  
  64.         out.println("  </BODY>");  
  65.         out.println("</HTML>");  
  66.         out.flush();  
  67.         out.close();  
  68.     }  
  69.   
  70.     /** 
  71.      * The doPost method of the servlet. <br> 
  72.      *  
  73.      * This method is called when a form has its tag value method equals to 
  74.      * post. 
  75.      *  
  76.      * @param request 
  77.      *            the request send by the client to the server 
  78.      * @param response 
  79.      *            the response send by the server to the client 
  80.      * @throws ServletException 
  81.      *             if an error occurred 
  82.      * @throws IOException 
  83.      *             if an error occurred 
  84.      */  
  85.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  86.             throws ServletException, IOException {  
  87.   
  88. //      System.out.println("in doPost.");  
  89.   
  90.         // response.setContentType("text/html; charset=UTF-8");  
  91.         // PrintWriter out = response.getWriter();  
  92.   
  93. //       String test = request.getParameter("name");  
  94. //       System.out.println("test is " + test);  
  95. //            
  96. //       String test1 = request.getParameter("age");  
  97. //       System.out.println("test1 is " + test1);  
  98.   
  99.         FileOperation fo = new FileOperation();  
  100.          try {  
  101.             DocumentVO documentVO = fo.doWriteFile(request);  
  102.             //這邊把序列號記錄到記錄文件中  
  103.             fo.logSequenceNumber(documentVO);  
  104.         } catch (FileUploadException e) {  
  105.             // TODO Auto-generated catch block  
  106.             e.printStackTrace();  
  107.             //這邊取消記錄文件中的序列號  
  108.             try {  
  109.                 fo.getLogFile();  
  110.             } catch (Exception e1) {  
  111.                 // TODO Auto-generated catch block  
  112.                 e1.printStackTrace();  
  113.             }  
  114.               
  115.         } catch (Exception e) {  
  116.             // TODO Auto-generated catch block  
  117.             e.printStackTrace();  
  118.             //這邊取消記錄文件中的序列號  
  119.             try {  
  120.                 fo.getLogFile();  
  121.             } catch (Exception e1) {  
  122.                 // TODO Auto-generated catch block  
  123.                 e1.printStackTrace();  
  124.             }  
  125.         }  
  126.            
  127.          // 向客戶端添加返回的標誌  
  128.         String status = "success";  
  129.         map.put("status", status);  
  130.         this.doCallbackMethod(request, response);  
  131.   
  132.     }  
  133.   
  134.     /** 
  135.      * Initialization of the servlet. <br> 
  136.      *  
  137.      * @throws ServletException 
  138.      *             if an error occurs 
  139.      */  
  140.     public void init() throws ServletException {  
  141.         // Put your code here  
  142.     }  
  143.   
  144.     /** 
  145.      * 經過返回字段的設置,向客戶端返回相應的信息,客戶端經過回調方法得到信息後處理 
  146.      *  
  147.      * @param request 
  148.      * @param response 
  149.      * @throws IOException 
  150.      */  
  151.     private void doCallbackMethod(HttpServletRequest request,  
  152.             HttpServletResponse response) {  
  153.   
  154.         PrintWriter writer = null;  
  155.         try {  
  156.             writer = response.getWriter();  
  157.             // FormatForJSON f = new FormatForJSON();  
  158.             // String json = f.object2json(map);  
  159.             JsonUtil json = JsonUtil.getInstanceFactory();  
  160.             json.fromObject(map);  
  161.             System.out.println("json is " + json.getResult());  
  162.             writer.print(json.getResult());  
  163.             writer.flush();  
  164.             writer.close();  
  165.   
  166.         } catch (IOException e) {  
  167.             e.printStackTrace();  
  168.         } finally {  
  169.             if (writer != null)  
  170.                 writer.close();  
  171.         }  
  172.     }  
  173. }  

 

 

4.  FileOperation.java 是文檔的操做類java

  

  

[java]  view plain copy
  1. package upload;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.ByteArrayOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileNotFoundException;  
  7. import java.io.FileOutputStream;  
  8. import java.io.FileReader;  
  9. import java.io.IOException;  
  10. import java.io.InputStream;  
  11. import java.io.OutputStream;  
  12. import java.text.SimpleDateFormat;  
  13. import java.util.ArrayList;  
  14. import java.util.Calendar;  
  15. import java.util.HashMap;  
  16. import java.util.Iterator;  
  17. import java.util.List;  
  18. import java.util.Map;  
  19.   
  20. import javax.servlet.http.HttpServletRequest;  
  21.   
  22. import org.apache.commons.fileupload.DiskFileUpload;  
  23. import org.apache.commons.fileupload.FileItem;  
  24.   
  25. import doc.util.ZipUtil;  
  26.   
  27.   
  28. /** 
  29.  * 文檔操做類 
  30.  * @author linwei 
  31.  * 
  32.  */  
  33. public class FileOperation {  
  34.   
  35.       
  36.     /** 
  37.      * 文檔的寫入方法 
  38.      * @param request 
  39.      * @throws Exception  
  40.      */  
  41.     public DocumentVO doWriteFile(HttpServletRequest request) throws Exception {  
  42.           
  43.           
  44.         //DiskFileUpload是commom-fileupload.jar包中的類  
  45.         DiskFileUpload diskFileUpload = new DiskFileUpload();  
  46.         //設置上傳文件的大小,默認大小爲100M  
  47.         diskFileUpload.setSizeMax(new Long(102400000));  
  48.         //設置緩衝大小  
  49.         diskFileUpload.setSizeThreshold(4096);  
  50.         //設置編碼方式  
  51.         diskFileUpload.setHeaderEncoding("GBK");  
  52.           
  53.         diskFileUpload.setHeaderEncoding("gb2312");  
  54.           
  55.           
  56.         //解析請求,返回一個集合  
  57.         List fileItem = diskFileUpload.parseRequest(request);  
  58.           
  59.         if(fileItem.size() == 0) {  
  60.             System.out.println("數量爲0.");  
  61.         }  
  62.           
  63.         //這邊是分別獲取到每一個的上傳文件  
  64.         Iterator it = fileItem.iterator();  
  65.         //這邊是循環每一個文件,獲取到每一個文件下的屬性,即FileItem對象  
  66.         List list = null;  
  67.         Map map = null;  
  68.         DocumentVO documentVO = null;  
  69.         File file = null;  
  70.         while(it.hasNext()) {  
  71.             FileItem fi = (FileItem)it.next();  
  72.             //這邊獲取文件流  
  73.             InputStream in = fi.getInputStream();  
  74.               
  75.             if(in == null) {  
  76.                 System.out.println("流是空的。");  
  77.             }  
  78.               
  79.             //這邊開始處理文件  
  80.             //若是是普通表單對象,則返回true,若是是文件表單字段,則返回false  
  81.             if(!fi.isFormField()) {  
  82.                 list = new ArrayList();  
  83.                 map = new HashMap();   
  84.                 //返回的文件名包括客戶機路徑  
  85.                 String filePath = fi.getName();  
  86.                 String fileName = this.getFileName(filePath);  
  87.                 String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);  
  88.                 fileName = fileName.substring(0,fileName.lastIndexOf("."));  
  89.                 documentVO = new DocumentVO();  
  90.                 documentVO.setFileName(fileName);  
  91.                 documentVO.setFileType(fileType);  
  92.                 documentVO = this.getSequenceNumber(documentVO);  
  93.   
  94.                 System.out.println("fileName is " + fileName);  
  95.                 list.add(in);  
  96.                   
  97.                 //for test  
  98. //              file = new File("D://Workspace//DocumentUpload//","linwei.txt");  
  99. //              fi.write(file);  
  100.                 //for test  
  101.               
  102.             }  
  103.         }  
  104.           
  105.         //開始調用上傳文檔方法  
  106.         return this.upload(documentVO, list);  
  107.     }  
  108.       
  109.       
  110.     /** 
  111.      * 上傳文檔的操做類 
  112.      * @param documentVO 
  113.      * @param list 
  114.      * @throws Exception  
  115.      */  
  116.     private DocumentVO upload(DocumentVO documentVO,List list) throws Exception {  
  117.           
  118.         if(documentVO == null || "".equals(documentVO)) {  
  119.              throw new Exception("documentVO 不能爲空!");             
  120.         }  
  121.           
  122.         if(list == null || list.size() == 0) {  
  123.              throw new Exception("沒有文件流。");  
  124.         }  
  125.           
  126.         InputStream in = (InputStream)list.get(0);  
  127.         return this.transferDocument(documentVO, in);         
  128.     }  
  129.       
  130.       
  131.     /** 
  132.      * 傳輸物理文件 
  133.      * @param documentVO 
  134.      * @param in 
  135.      * @return  
  136.      */  
  137.     private DocumentVO transferDocument(DocumentVO documentVO,Object bytesStream) {  
  138.           
  139.         //這邊先寫死了一個路徑,正確的應該是寫在配置文件中的  
  140.         String path = "D://Workspace//DocumentUpload//";  
  141.         //**********************************************  
  142.         //這邊傳遞的文件不能是路徑,必須是已經拼裝好的文件具體地址了  
  143.         String fileAbsolutePath = path + documentVO.getSequenceNumber();  
  144.           
  145.         if(bytesStream instanceof InputStream) {  
  146.             //開始進行壓縮  
  147.             ZipUtil zipUtil = new ZipUtil();  
  148.             Map map = new HashMap();  
  149.             //這邊傳遞的壓縮文件的名字最好是文件的全名  
  150.             map.put(documentVO.getFileName()+"."+documentVO.getFileType(), (InputStream)bytesStream);  
  151.             try {  
  152.                 zipUtil.zip(fileAbsolutePath, map);  
  153.                 System.out.println("OK");  
  154.             } catch (Exception e) {  
  155.                 // TODO Auto-generated catch block  
  156.                 e.printStackTrace();  
  157.                 //若是出錯了的話,就用常規的文件保存方式  
  158.                 this.write((InputStream)bytesStream, fileAbsolutePath,documentVO);  
  159.             }   
  160.         } else {  
  161.             this.write((OutputStream)bytesStream, fileAbsolutePath,documentVO);  
  162.         }  
  163.           
  164.         //這邊把序列號做爲名字參數傳遞出去  
  165.         return documentVO;  
  166.     }  
  167.       
  168.       
  169.     /**  
  170.      * 取得存儲時候的文件名,最後也是根據這個名字去數據庫中查詢的  
  171.      * @param fileName  
  172.      * @return   
  173.      */  
  174.     private DocumentVO getSequenceNumber(DocumentVO documentVO) {  
  175.           
  176.         //這邊文件名字(fileName)傳遞進來以便後面可使用  
  177.         Calendar c = Calendar.getInstance();  
  178.         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");  
  179.         documentVO.setSequenceNumber(dateFormat.format(c.getTime()));  
  180.         return documentVO;  
  181.     }  
  182.       
  183.       
  184.     /** 
  185.      * 從路徑中取得文件名 
  186.      * @param fileName 
  187.      * @return  
  188.      */  
  189.     private String getFileName(String filePath) {  
  190.           
  191.         int pos = filePath.lastIndexOf(File.separator);  
  192. //      System.out.println("File.separator is " + File.separator);  
  193.         if(pos > 0) {  
  194.             //position爲該字符串最右邊出現的位置,substring(number)獲取到該位置以後的字符串  
  195.             return filePath.substring(pos + 1);  
  196.         } else {  
  197.             return filePath;  
  198.         }  
  199.     }  
  200.       
  201.       
  202.     /** 
  203.      * 把輸入流對象持久化 
  204.      * @param in 
  205.      */  
  206.     public void write(InputStream in,String absolutePath,DocumentVO documentVO) {  
  207.           
  208.         FileOutputStream file = null;  
  209.   
  210.         try {  
  211.             // 檢查文件路徑  
  212.             this.checkFile(new File(absolutePath));  
  213.             absolutePath = absolutePath + "//" + documentVO.getFileName() + "." + documentVO.getFileType();   
  214.             file = new FileOutputStream(absolutePath);  
  215.   
  216.             int length = 0;  
  217.             byte[] buffer = new byte[10240];  
  218.   
  219.             while ((length = in.read(buffer, 010240)) > -1) {  
  220.                 file.write(buffer, 0, length);  
  221.             }  
  222.   
  223.         } catch (FileNotFoundException e) {  
  224.             // TODO Auto-generated catch block  
  225.             e.printStackTrace();  
  226.         } catch (IOException e) {  
  227.             // TODO Auto-generated catch block  
  228.             e.printStackTrace();  
  229.         } finally {  
  230.   
  231.             try {  
  232.                 if (in != null)  
  233.                     in.close();  
  234.                 if (file != null)  
  235.                     file.close();  
  236.             } catch (IOException e) {  
  237.                 // TODO Auto-generated catch block  
  238.                 e.printStackTrace();  
  239.             }  
  240.         }  
  241.     }  
  242.       
  243.     /** 
  244.      * 把輸出流對象持久化 
  245.      * @param in 
  246.      */  
  247.     public void write(OutputStream out,String absolutePath,DocumentVO documentVO) {  
  248.   
  249.         FileOutputStream file = null;  
  250.           
  251.         try {  
  252.             // 檢查文件路徑  
  253.             this.checkFile(new File(absolutePath));  
  254.             absolutePath = absolutePath + "//" + documentVO.getFileName() + "." + documentVO.getFileType();   
  255.             file = new FileOutputStream(absolutePath);  
  256.             ByteArrayOutputStream baos = (ByteArrayOutputStream)out;  
  257.             file.write(baos.toByteArray());  
  258.               
  259.         } catch (FileNotFoundException e) {  
  260.             // TODO Auto-generated catch block  
  261.             e.printStackTrace();  
  262.         } catch (IOException e) {  
  263.             // TODO Auto-generated catch block  
  264.             e.printStackTrace();  
  265.         } finally {  
  266.   
  267.             try {  
  268.                 if (out != null)  
  269.                     out.close();  
  270.                 if (file != null)  
  271.                     file.close();  
  272.             } catch (IOException e) {  
  273.                 // TODO Auto-generated catch block  
  274.                 e.printStackTrace();  
  275.             }  
  276.         }  
  277.     }  
  278.       
  279.       
  280.       
  281.     /** 
  282.      * 檢查文件的路徑是否存在,若是不存在則建立該路徑,以便建立該文件 
  283.      *  
  284.      * @param file 
  285.      */  
  286.     private void checkFilePath(File file) {  
  287.         this.checkFile(file.getParentFile());  
  288.     }  
  289.       
  290.   
  291.     /** 
  292.      * 檢查路徑 
  293.      * @param file 
  294.      * 路徑的最後一個節點, 如C:/1/2/3/d.file 則將該File對象的.getParentFile傳入 即C:/1/2/3 
  295.      */  
  296.     private void checkFile(File file) {  
  297.         //若是該文件對象不存在  
  298.         if(!file.exists()) {  
  299.             //若是文件對象不存在,則繼續查詢其父類的文件對象,並建立目錄  
  300.             this.checkFilePath(file.getParentFile());  
  301.             file.mkdir();  
  302.         }  
  303.     }  
  304.       
  305.       
  306.     /** 
  307.      * 這邊記錄已上傳文件的序列號 
  308.      * @param documentVO 
  309.      * @throws Exception 
  310.      */  
  311.     public void logSequenceNumber(DocumentVO documentVO) throws Exception {  
  312.           
  313.         if(documentVO != null && !"".equals(documentVO)) {  
  314.             if(documentVO.getSequenceNumber() != null && !"".equals(documentVO.getSequenceNumber())) {  
  315.   
  316.                 String sequenceNumber = documentVO.getSequenceNumber() + ",";  
  317.                 this.logSeqToFile(sequenceNumber);  
  318.             }  
  319.         }  
  320.     }  
  321.       
  322.       
  323.     /** 
  324.      * 把傳遞進來的序列號加入到文件的最後端,按照英文狀態下的,分隔 
  325.      * @param sequenceNumber 
  326.      * @throws IOException  
  327.      */  
  328.     private void logSeqToFile(String sequenceNumber) throws IOException {  
  329.            
  330.         //這邊先寫死了一個路徑,正確的應該是寫在配置文件中的  
  331.         String path = "D://Workspace//DocumentUpload//node.txt";  
  332.         File file = new File(path);  
  333.         FileOutputStream out = new FileOutputStream(file,true);  
  334.         byte[] byte1 = new byte[512];  
  335.         int b = sequenceNumber.length();  
  336.         //這邊須要寫入字節  
  337.         out.write(sequenceNumber.getBytes());  
  338.         out.close();  
  339.     }  
  340.       
  341.       
  342.       
  343.     /** 
  344.      * 讀取記錄文件中的內容並返回 
  345.      * @return  
  346.      * @throws Exception 
  347.      */  
  348.     public String getLogFile() throws Exception {  
  349.           
  350.         String str = "";  
  351.         //這邊先寫死了一個路徑,正確的應該是寫在配置文件中的  
  352.         String path = "D://Workspace//DocumentUpload//node.txt";  
  353.         File file = new File(path);  
  354.         BufferedReader b = new BufferedReader(new FileReader(file));  
  355.         String i;  
  356.         while((i = b.readLine()) != null) {  
  357.             str += i;  
  358.         }  
  359.         return str;  
  360.     }  
  361.       
  362.       
  363.       
  364. }  

 

 5.  文檔壓縮類 ZipUtilnode

 

  

[java]  view plain copy
  1. package doc.util;  
  2.   
  3. import java.io.FileOutputStream;  
  4. import java.io.InputStream;  
  5. import java.util.Iterator;  
  6. import java.util.Map;  
  7. import java.util.Set;  
  8.   
  9. import org.apache.tools.zip.ZipEntry;  
  10. import org.apache.tools.zip.ZipOutputStream;  
  11.   
  12.   
  13. /** 
  14.  * 對文檔進行壓縮的類 
  15.  * @author linwei 
  16.  * 
  17.  */  
  18. public class ZipUtil {  
  19.   
  20.     // 要壓縮文件的最大值  
  21.     public final static long maxSize = 100000000;// 這個能夠配置到配置文件中 100MB  
  22.     public final static int BUFFERSIZE = 2048 ;   //  
  23.     private static final ThreadLocal currentZipName = new ThreadLocal();  
  24.   
  25.       
  26.     /** 
  27.      * 根據輸出路徑對文件流進行壓縮輸出 
  28.      * @param fileOutPath 
  29.      * @param mapInputStreams 
  30.      * @throws Exception 
  31.      */  
  32.     public void zip(String fileOutPath, Map mapInputStreams) throws Exception {  
  33.           
  34.         if (fileOutPath == null || "".equals(fileOutPath)) {  
  35.             return;  
  36.         }  
  37.           
  38.         if (mapInputStreams != null && mapInputStreams.size() > 0) {  
  39.             Set entrys = mapInputStreams.entrySet();  
  40.             FileOutputStream out = new FileOutputStream(fileOutPath);  
  41.             //Java壓縮專用類  
  42.             ZipOutputStream zip = new ZipOutputStream(out);  
  43.             String fileName = null;  
  44.             InputStream inputStream = null;  
  45.             Iterator it = entrys.iterator();  
  46.             while (it.hasNext()) {  
  47.                 Map.Entry entry = (Map.Entry) it.next();  
  48.                 fileName = (String) entry.getKey();  
  49.                 inputStream = (InputStream) entry.getValue();  
  50.                 zip(zip, inputStream, fileName);  
  51.             }  
  52.             zip.close();  
  53.         }  
  54.     }  
  55.       
  56.   
  57.     /** 
  58.      * 壓縮文件 
  59.      * @param out 
  60.      * @param inputStream 
  61.      * @param fileName 
  62.      * @throws Exception 
  63.      */  
  64.     private void zip(ZipOutputStream out, InputStream inputStream,  
  65.             String fileName) throws Exception {  
  66.           
  67.           
  68.         //for test  
  69.         /*File file1 = new File("D://Workspace//DocumentUpload//","test.txt"); 
  70.         BufferedOutputStream out1 = new BufferedOutputStream(new FileOutputStream(file1)); 
  71.          
  72.         int b; 
  73.         byte[] buf = new byte[2048]; 
  74.         while((b = inputStream.read(buf)) != -1) { 
  75.             out1.write(buf); 
  76.         } 
  77.  
  78.         //注意,這邊三點最好所有都寫完整,要不會出問題 
  79.         //將緩衝區中的數據所有寫出。 
  80.         out1.flush(); 
  81.         inputStream.close(); 
  82.         out1.close();*/  
  83.         //for test  
  84.           
  85.         //開始寫入新的 ZIP 文件條目並將流定位到條目數據的開始處  
  86.         //**********************************************  
  87.         //這邊請注意,ZipOutputStream和ZipEntry都請用org.apache.tools.zip包下的類,  
  88.         //這樣就能夠解決壓縮文件名亂碼的問題了。  
  89.         out.putNextEntry(new org.apache.tools.zip.ZipEntry(fileName));  
  90.         int b1;  
  91.         byte[] buf1 = new byte[BUFFERSIZE];  
  92.         while ((b1 = inputStream.read(buf1)) != -1) {  
  93.             out.write(buf1, 0, b1);  
  94.         }  
  95.         if (inputStream != null) {  
  96.             inputStream.close();  
  97.             inputStream = null;  
  98.         }  
  99.     }  
  100. }  

 

6.  文檔的實體類 DocumentVOjquery

 

[java]  view plain copy
  1. package upload;  
  2.   
  3.   
  4. /** 
  5.  * 用來傳遞參數的 
  6.  * @author linwei 
  7.  * 
  8.  */  
  9. public class DocumentVO {  
  10.   
  11.     private String fileName;  
  12.     private String sequenceNumber;  
  13.     private String fileType;  
  14.   
  15.     public String getFileName() {  
  16.         return fileName;  
  17.     }  
  18.   
  19.     public void setFileName(String fileName) {  
  20.         this.fileName = fileName;  
  21.     }  
  22.   
  23.     public String getSequenceNumber() {  
  24.         return sequenceNumber;  
  25.     }  
  26.   
  27.     public void setSequenceNumber(String sequenceNumber) {  
  28.         this.sequenceNumber = sequenceNumber;  
  29.     }  
  30.   
  31.     public String getFileType() {  
  32.         return fileType;  
  33.     }  
  34.   
  35.     public void setFileType(String fileType) {  
  36.         this.fileType = fileType;  
  37.     }  
  38.       
  39. }  

 

 

7.  文檔調閱界面web

 

 

[java]  view plain copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>  
  2. <%@ page import="upload.*" %>  
  3.   
  4. <%  
  5. String path = request.getContextPath();  
  6. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  7. %>  
  8.   
  9. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  10. <html>  
  11.   <head>  
  12.     <base href="<%=basePath%>">  
  13.       
  14.     <title>My JSP 'docUpload.jsp' starting page</title>  
  15.       
  16.     <meta http-equiv="pragma" content="no-cache">  
  17.     <meta http-equiv="cache-control" content="no-cache">  
  18.     <meta http-equiv="expires" content="0">      
  19.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  20.     <meta http-equiv="description" content="This is my page">  
  21.     <!--  
  22.     <link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">  
  23.     -->  
  24.       
  25.     <mce:script type="text/javascript" src="resources/jquery.js" mce_src="resources/jquery.js"></mce:script>  
  26.     <mce:script type="text/javascript" src="resources/upload/fileUploadUtil.js" mce_src="resources/upload/fileUploadUtil.js"></mce:script>  
  27.       
  28.   </head>  
  29.     
  30.     
  31.   <body>  
  32.       <%  
  33.          FileOperation f = new FileOperation();  
  34.          String str = f.getLogFile();  
  35.          String[] s = str.split(",");  
  36.        %>   
  37.       <form action="" name="form1">   
  38.        <table id="upload" border="1">  
  39.                <tr>  
  40.                   <td width="20%">文檔鏈接</td>  
  41.                </tr>  
  42.                <%  
  43.                      for(int i=0;i<s.length;i++) {  
  44.                          
  45.                     %>  
  46.                  <tr>  
  47.                    <td><a href="/AJAX/servlet/fileDownload?id=<%=s[i]%>"><%=s[i] %></a></td>             
  48.                  </tr>  
  49.                   <%  
  50.                   }  
  51.                  %>  
  52.          </table>   
  53.        </form>  
  54.   </body>  
  55. </html>  

 

 

8.  調閱Servletajax

 

 

[java]  view plain copy
  1. package upload;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.FileOutputStream;  
  8. import java.io.IOException;  
  9. import java.io.InputStream;  
  10.   
  11. import javax.servlet.ServletException;  
  12. import javax.servlet.ServletOutputStream;  
  13. import javax.servlet.http.HttpServlet;  
  14. import javax.servlet.http.HttpServletRequest;  
  15. import javax.servlet.http.HttpServletResponse;  
  16.   
  17.   
  18. /** 
  19.  * 文檔下載服務類 
  20.  * @author linwei 
  21.  * 
  22.  */  
  23. public class fileDownload extends HttpServlet {  
  24.   
  25.     /** 
  26.      * Constructor of the object. 
  27.      */  
  28.     public fileDownload() {  
  29.         super();  
  30.     }  
  31.   
  32.     /** 
  33.      * Destruction of the servlet. <br> 
  34.      */  
  35.     public void destroy() {  
  36.         super.destroy(); // Just puts "destroy" string in log  
  37.         // Put your code here  
  38.     }  
  39.   
  40.     /** 
  41.      * The doGet method of the servlet. <br> 
  42.      * 
  43.      * This method is called when a form has its tag value method equals to get. 
  44.      *  
  45.      * @param request the request send by the client to the server 
  46.      * @param response the response send by the server to the client 
  47.      * @throws ServletException if an error occurred 
  48.      * @throws IOException if an error occurred 
  49.      */  
  50.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  51.             throws ServletException, IOException {  
  52.   
  53.         System.out.println("doGet");  
  54.         this.doDownload(request, response);  
  55.     }  
  56.   
  57.     /** 
  58.      * The doPost method of the servlet. <br> 
  59.      * 
  60.      * This method is called when a form has its tag value method equals to post. 
  61.      *  
  62.      * @param request the request send by the client to the server 
  63.      * @param response the response send by the server to the client 
  64.      * @throws ServletException if an error occurred 
  65.      * @throws IOException if an error occurred 
  66.      */  
  67.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  68.             throws ServletException, IOException {  
  69.           
  70.         System.out.println("doPost");  
  71.         this.doDownload(request, response);  
  72.     }  
  73.   
  74.     /** 
  75.      * Initialization of the servlet. <br> 
  76.      * 
  77.      * @throws ServletException if an error occurs 
  78.      */  
  79.     public void init() throws ServletException {  
  80.         // Put your code here  
  81.     }  
  82.   
  83.   
  84.     /** 
  85.      * 此方法被doPost和doGet方法調用,用來統一調用文檔 
  86.      * @param request 
  87.      * @param response 
  88.      * @throws ServletException 
  89.      * @throws IOException 
  90.      */  
  91.     public void doDownload(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException{      
  92.   
  93.         InputStream in = null;  
  94.           
  95.         response.setContentType("application/x-download; charset=gb2312");   
  96.         //取得文件分割符  
  97.         String file_separator = System.getProperty( "file.separator" );  
  98.         //這邊本身假設一個顯示的文件名  
  99.         String displayname = "temp111.zip";  
  100.         //這邊路徑也是先寫死的,後面能夠改   
  101.         String path = "D://Workspace//DocumentUpload//" + request.getParameter("id");  
  102.         response.addHeader("Content-Disposition","attachment;filename=" + new String(displayname.getBytes("gb2312"),"iso-8859-1"));   
  103.           
  104.         try {  
  105.             in = new FileInputStream(path);  
  106.             this.downLoad(in, response);  
  107.         } catch(Exception e) {  
  108.               
  109.         } finally {  
  110.             if(in != null)  
  111.                 in.close();  
  112.         }  
  113.     }  
  114.       
  115.       
  116.     /** 
  117.      * write file stream to servlet output stream  
  118.      * @param is 
  119.      * @param response 
  120.      * @throws Exception  
  121.      */  
  122.     private void downLoad(InputStream in, HttpServletResponse response) throws Exception {  
  123.       
  124.         BufferedInputStream bufferInput = new BufferedInputStream(in);  
  125.         ServletOutputStream out = null;  
  126.           
  127.         try {  
  128.             byte[] buffer = new byte[10240];  
  129.             out = response.getOutputStream();  
  130.             int len;  
  131.             while((len = bufferInput.read(buffer)) != -1) {  
  132.                 out.write(buffer, 0, len);  
  133.             }  
  134.             out.flush();      
  135.             response.setStatus(response.SC_OK);  
  136.             response.flushBuffer();  
  137.         } catch(Exception e) {  
  138.             throw e;  
  139.         } finally {  
  140.             if (out != null) {  
  141.                 out.close();  
  142.             }  
  143.             if (bufferInput != null) {  
  144.                 bufferInput.close();  
  145.             }  
  146.             if (in != null) {  
  147.                 in.close();  
  148.             }  
  149.         }  
  150.     }     
  151. }  

 以上只是一些簡單的過程,具體的一些信息仍是須要按照不一樣的需求進行修改的
相關文章
相關標籤/搜索