打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
通过JQuery中的AJAX函数来实现文档的上传,压缩,下载
1.   文档上传的一个简单界面 docUpload.jsp:


  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 为上传下载文档都需要引入的JS

  

  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 是上传的Servlet

 

  

  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 是文档的操作类

  

  

  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.  文档压缩类 ZipUtil

 

  

  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.  文档的实体类 DocumentVO

 

  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.  文档调阅界面

 

 

  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.  调阅Servlet

 

 

  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. }  

 

 

 

 以上只是一些简单的过程,具体的一些信息还是需要按照不同的需求进行修改的。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
servlet 和JSP的上传下载
Struts2文件下载
文件上传
jsp文件下载完整方法
JfreeChart学习
微信公众平台 Java SDK
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服