使用jspSmartUpload组件进行文件上传、下载、批量下载

 jspSmartUpload组件是一个可以免费使用的文件上传与下载组件。用户可以把他安装在web服务器上,再进行使用。
       jspSmartUpload组件使用非常简单。在jsp文件中仅需要写几行代码就可以实现文件的上传、下载。并能够全程控制上传。利用jspSmartUpload|组件提供的对象及其操作方法,可以获得全部上传、下载的信息,如文件名,大小,类型、扩展名。。。。以方便文件的存取;能对上传的文件在大小、类型等方面做出限制。这样就可以过滤掉不符合要求的文件;下载灵活。只须写很少的代码就能把web服务器变成文件服务器,不管文件在不在web服务器的目录下,都可以利用该组件进行下载。

     在使用jspSmartUpload时,必须将该组件放在项目中相应的目录里,如:WebRoot/WEB-INF/lib

 一、文件上传
         下面是一个jsp页面,表单中有4个文件输入文本框,可以同时上传4个文件:

使用jspSmartUpload组件进行文件上传、下载、批量下载
1 <form action="file?file=upLoadByjs" method="post" ENCTYPE="multipart/form-data">
2       <input type="file" name=file1" size="30"><Br>
3       <input type="file" name=file2" size="30"><Br>
4       <input type="file" name=file3" size="30"><Br>
5       <input type="file" name=file4" size="30"><Br>
6       <input type="submit" value="上传">
7     </form>
使用jspSmartUpload组件进行文件上传、下载、批量下载

     当然可以设置同时上传更多的文件......
     servlet处理程序:

使用jspSmartUpload组件进行文件上传、下载、批量下载
 1 String path ="D:/work space/JSP workspace/jsp_servlet_upAndLoad/file/upLoad";
 2     //新建一个jsmartUpLoad对象
 3     SmartUpload smartUpload = new SmartUpload();
 4     //上传初始化
 5     smartUpload.initialize(this.getServletConfig(),request,response);
 6     try {
 7       //设定上传限制
 8       //限制每个上传文件的最大长度;将最大设定为1024*1024*20
 9       smartUpload.setMaxFileSize(1024*1024*10);   
10       //限制总上传数据的长度
11       smartUpload.setTotalMaxFileSize(1024*1024*20);
12       //限制允许上传的文件类型、允许doc、txt、bat文件
13       smartUpload.setAllowedFilesList("doc,txt,bat");
14       //限制禁止上传的文件类型,禁止exe、jsp、和没有扩展名的文件
15       smartUpload.setDeniedFilesList("exe,jsp,,");
16       //上传文件
17       smartUpload.upload();
18       //将文件保存到指定的目录下
19       smartUpload.save(path);
20     } catch (SQLException e) {
21       e.printStackTrace();
22     } catch (SmartUploadException e) {
23       e.printStackTrace();
24     }
25     
26     //逐一提取文件信息,同时输出上传文件的信息
27     for (int i = 0; i < smartUpload.getFiles().getCount(); i++) {
28       com.jspsmart.upload.File  myFile =smartUpload.getFiles().getFile(i);
29       //若文件表单中的文件选项没有选择文件则继续
30       if(myFile.isMissing())
31         continue;
32       //显示当前文件的信息
33       response.setContentType("text/html;charset=utf-8");
34       PrintWriter out = response.getWriter();
35       out.println("<table border='1'>");
36       out.println("<tr><td>表单选项</td><td>"+myFile.getFieldName()+"</td></tr>");
37       out.println("<tr><td>文件长度:</td><td>"+myFile.getSize()+"</td></tr>");
38       out.println("<tr><td>文件名</td><td>"+myFile.getFileName()+"</td></tr>");
39       out.println("<tr><td>文件扩展名</td><td>"+myFile.getFileExt()+"</td></tr>");
40       out.println("<tr><td>文件全名</td><td>"+myFile.getFilePathName()+"</td></tr>");
41       out.println("</table><br>");
42     }
使用jspSmartUpload组件进行文件上传、下载、批量下载

 


该程序直接使用SmartUploa对象来实现文件上传。在申请对象后,必须要对其进行初始化:smartUpload.initialize(this.getServletConfig(),request,response);

二、文件下载
     使用jspSmartUpload组件进行文件下载,可以非常简单:
      jsp页面:

1    <a href="${pageContext.request.contextPath }/file1?file=downByJsmart&name=user.txt">下载user</a>

   处理程序:

使用jspSmartUpload组件进行文件上传、下载、批量下载
 1 //获取下载文件名
 2     String fileName = request.getParameter("name");
 3     //新建一个smartUpload对象
 4     SmartUpload smartUpload = new SmartUpload();
 5     //初始化
 6     smartUpload.initialize(this.getServletConfig(), request, response);
 7     //设定contentDisposition为null以禁止浏览器自动打开文件
 8     //保证单击链接后是下载文件。
 9     smartUpload.setContentDisposition(null);
10     //下载文件
11     try {
12       smartUpload.downloadFile("D:/work space/JSP workspace/jsp_servlet_upAndLoad/file/upLoad/"+fileName);
13     } catch (SmartUploadException e) {
14       e.printStackTrace();
15     }



详细代码(包含批量下载)

一、简介

SmartUpload一种Java上传组件包,可以轻松的实现文件的上传及下载功能。

使用该组件可以轻松的实现上传文件的限制,也可以轻易的取得文件上传的名称、后缀、大小等。


二、详细介绍【百度百科有相对详细的介绍及使用


三、具体实现例子【jsp+SmartUpload】

项目目录

使用jspSmartUpload组件进行文件上传、下载、批量下载


web.xml配置

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="3.0"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">  
  7.   <display-name></display-name>  
  8.   <servlet>  
  9.     <description>This is the description of my J2EE component</description>  
  10.     <display-name>This is the display name of my J2EE component</display-name>  
  11.     <servlet-name>SmartUploadServlet</servlet-name>  
  12.     <servlet-class>com.wuhn.smartupload.servlet.SmartUploadServlet</servlet-class>  
  13.   </servlet>  
  14.   <servlet>  
  15.     <description>This is the description of my J2EE component</description>  
  16.     <display-name>This is the display name of my J2EE component</display-name>  
  17.     <servlet-name>SmartDownloadServlet</servlet-name>  
  18.     <servlet-class>com.wuhn.smartupload.servlet.SmartDownloadServlet</servlet-class>  
  19.   </servlet>  
  20.   <servlet>  
  21.     <description>This is the description of my J2EE component</description>  
  22.     <display-name>This is the display name of my J2EE component</display-name>  
  23.     <servlet-name>BatchSmartDownloadServlet</servlet-name>  
  24.     <servlet-class>com.wuhn.smartupload.servlet.BatchSmartDownloadServlet</servlet-class>  
  25.   </servlet>  
  26.   
  27.   <!-- 上传servlet -->    
  28.   <servlet-mapping>  
  29.     <servlet-name>SmartUploadServlet</servlet-name>  
  30.     <url-pattern>/SmartUploadServlet.do</url-pattern>  
  31.   </servlet-mapping>  
  32.   <!-- 下载servlet -->    
  33.   <servlet-mapping>  
  34.     <servlet-name>SmartDownloadServlet</servlet-name>  
  35.     <url-pattern>/SmartDownloadServlet.do</url-pattern>  
  36.   </servlet-mapping>  
  37.   <!-- 批量下载servlet -->      
  38.   <servlet-mapping>  
  39.     <servlet-name>BatchSmartDownloadServlet</servlet-name>  
  40.     <url-pattern>/BatchSmartDownloadServlet.do</url-pattern>  
  41.   </servlet-mapping>    
  42.   <welcome-file-list>  
  43.     <welcome-file>index.jsp</welcome-file>  
  44.   </welcome-file-list>  
  45. </web-app>  


后台servlet

SmartUploadServlet.java

[java] view plain copy
  1. package com.wuhn.smartupload.servlet;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.io.PrintWriter;  
  6. import java.sql.SQLException;  
  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 com.jspsmart.upload.SmartUpload;  
  14. import com.jspsmart.upload.SmartUploadException;  
  15.   
  16. /** 
  17.  * @author wuhn 
  18.  * @创建时间 2015-12-08 
  19.  * @功能 SmartUpload 上传  
  20.  * **/  
  21. public class SmartUploadServlet extends HttpServlet {  
  22.   
  23.     /** 
  24.      * The doGet method of the servlet.  
  25.      */  
  26.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  27.             throws ServletException, IOException {  
  28.         doPost(request,response);//默认post  
  29.           
  30.     }  
  31.   
  32.     /** 
  33.      * The doPost method of the servlet.  
  34.      * 
  35.      */  
  36.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  37.             throws ServletException, IOException {  
  38.         //设置上传文件保存路径  
  39.         String filePath = getServletContext().getRealPath("/")+"images";  
  40.         File file = new File(filePath);  
  41.         if(!file.exists()){  
  42.             file.mkdir();  
  43.         }  
  44.           
  45.         SmartUpload smartUpload = new SmartUpload();  
  46.         //初始化对象  
  47.         smartUpload.initialize(getServletConfig(), request, response);  
  48.         //设置上传文件  
  49.         smartUpload.setMaxFileSize(1024*1024*10);  
  50.         //设置所有文件的大小  
  51.         smartUpload.setTotalMaxFileSize(1024*1024*100);  
  52.         //设置文件的类型  
  53.         smartUpload.setAllowedFilesList("txt,jpg,gif");  
  54.         String result = "上传成功!";  
  55.         //设置禁止上传的文件类型  
  56.         try {  
  57.             smartUpload.setDeniedFilesList("rar,jsp,js");  
  58.             //上传文件  
  59.             smartUpload.upload();  
  60.             //保存文件  
  61.             int count = smartUpload.save(filePath);       
  62.         } catch (Exception e) {  
  63.             //捕捉Exception异常 ,不然捕捉到异常  
  64.             result = "上传失败!";  
  65.             if(e.getMessage().indexOf("1015") != -1){  
  66.                 result = "上传失败:上传文件类型不正确!";  
  67.             }else if (e.getMessage().indexOf("1010") != -1) {  
  68.                 result = "上传失败:上传文件类型不正确!";  
  69.             }else if (e.getMessage().indexOf("1105") != -1) {  
  70.                 result = "上传失败:上传文件大小大于允许上传的最大值!";  
  71.             }else if (e.getMessage().indexOf("1110") != -1) {  
  72.                 result = "上传失败:上传文件总大小大于允许上传总大小的最大值!";  
  73.             }  
  74.             e.printStackTrace();  
  75.         }  
  76.           
  77.         //获取上传文件的属性  
  78.         for(int i=0;i<smartUpload.getFiles().getCount();i++){  
  79.             com.jspsmart.upload.File tempFile = smartUpload.getFiles().getFile(i);  
  80.             System.out.println("***************");  
  81.             System.out.println("表单中name的值:"+tempFile.getFileName());  
  82.             System.out.println("上传文件名:"+tempFile.getFileName());  
  83.             System.out.println("上传文件大小:"+tempFile.getSize());  
  84.             System.out.println("上传文件的拓展名:"+tempFile.getFileExt());  
  85.             System.out.println("上传文件全名:"+tempFile.getFilePathName());  
  86.             System.out.println("***************");  
  87.         }  
  88.           
  89.         System.out.println("上传结果:"+result);  
  90.         request.setAttribute("result", result);  
  91.         request.getRequestDispatcher("/jsp/01.jsp").forward(request, response);  
  92.           
  93.           
  94.     }  
  95.   
  96. }  

SmartDownloadServlet.java

[java] view plain copy
  1. package com.wuhn.smartupload.servlet;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import com.jspsmart.upload.SmartUpload;  
  12. import com.jspsmart.upload.SmartUploadException;  
  13.   
  14. /** 
  15.  * @author wuhn 
  16.  * @创建时间 2015-12-08 
  17.  * @功能 SmartUpload 下载  
  18.  * **/  
  19. public class SmartDownloadServlet extends HttpServlet {  
  20.   
  21.     /** 
  22.      * The doGet method of the servlet. <br> 
  23.      * 
  24.      */  
  25.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  26.             throws ServletException, IOException {  
  27.         doPost(request,response);  
  28.           
  29.     }  
  30.   
  31.     /** 
  32.      * The doPost method of the servlet. <br> 
  33.      */  
  34.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  35.             throws ServletException, IOException {  
  36.         String result = "下载成功";  
  37.         //获取下载的文件名  
  38.         String filename = request.getParameter("filename");  
  39.         //下载  
  40.         SmartUpload smartUpload = new SmartUpload();  
  41.         smartUpload.initialize(getServletConfig(), request, response);  
  42.         smartUpload.setContentDisposition(null);//取消默认打开方式  
  43.         try {  
  44.             smartUpload.downloadFile("/images/"+filename);  
  45.         } catch (Exception e) {  
  46.             result = "下载失败";  
  47.             System.out.println("********异常处理********");  
  48.             if(e.getMessage().indexOf("系统找不到指定的路径。") != -1){  
  49.                 result = "下载失败:文件不存在!";  
  50.             }  
  51.             e.printStackTrace();  
  52.         }  
  53.           
  54.         request.setAttribute("result", result);  
  55.         request.getRequestDispatcher("/jsp/02.jsp").forward(request, response);  
  56.           
  57.           
  58.     }  
  59.   
  60. }  

BatchSmartDownloadServlet.java

[java] view plain copy
  1. package com.wuhn.smartupload.servlet;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.IOException;  
  6. import java.io.PrintWriter;  
  7. import java.util.Iterator;  
  8. import java.util.zip.ZipEntry;  
  9. import java.util.zip.ZipOutputStream;  
  10.   
  11. import javax.servlet.ServletException;  
  12. import javax.servlet.http.HttpServlet;  
  13. import javax.servlet.http.HttpServletRequest;  
  14. import javax.servlet.http.HttpServletResponse;  
  15.   
  16. /** 
  17.  * @author wuhn 
  18.  * @创建时间 2015-12-09 
  19.  * @功能 SmartUpload 批量下载 
  20.  * **/  
  21. public class BatchSmartDownloadServlet extends HttpServlet {  
  22.   
  23.     /** 
  24.      * The doGet method of the servlet.  
  25.      */  
  26.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  27.             throws ServletException, IOException {  
  28.         doPost(request,response);  
  29.           
  30.     }  
  31.   
  32.     /** 
  33.      * The doPost method of the servlet.  
  34.      */  
  35.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  36.             throws ServletException, IOException {  
  37.         //设置下载相应信息  
  38.         response.setContentType("application/x-msdownload");  
  39.         response.setHeader("Content-Disposition""attachment;filename=test.zip");  
  40.           
  41.         //下载路径  
  42.         String path = getServletContext().getRealPath("/")+"images/";  
  43.         //获取下载的所有文件名  
  44.         String[] filenames = request.getParameterValues("filename");  
  45.         String str = "";  
  46.         String rt = "\r\n";  
  47.         //设置压缩信息  
  48.         ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());  
  49.         //获取需要下载的文件  
  50.         for(String filename:filenames){  
  51.             str += filename + rt;  
  52.             File file = new File(path + filename);  
  53.             zipOutputStream.putNextEntry(new ZipEntry(filename));//加入压缩文件  
  54.             FileInputStream fileInputStream = new FileInputStream(file);  
  55.             byte b[] = new byte[1024];  
  56.             int n=0;  
  57.             while ((n=fileInputStream.read(b)) != -1) {  
  58.                 zipOutputStream.write(b, 0, n);  
  59.             }  
  60.             zipOutputStream.flush();  
  61.             fileInputStream.close();  
  62.         }  
  63.           
  64.         zipOutputStream.setComment("download success:" + rt +str);//zip注释信息  
  65.         zipOutputStream.flush();  
  66.         zipOutputStream.close();  
  67.           
  68.           
  69.     }  
  70.   
  71. }  


前台页面jsp

[html] view plain copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE>  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'index.jsp' starting page</title>  
  13.     <meta http-equiv="pragma" content="no-cache">  
  14.     <meta http-equiv="cache-control" content="no-cache">  
  15.     <meta http-equiv="expires" content="0">      
  16.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  17.     <meta http-equiv="description" content="This is my page">  
  18.     <!-- 
  19.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  20.     -->  
  21.   </head>  
  22.     
  23.   <body>  
  24.     <a target="_blank" href="<%=path%>/jsp/01.jsp">上传01</a>  
  25.     <br>  
  26.     <a target="_blank" href="<%=path%>/jsp/02.jsp">下载02</a>  
  27.     <br>  
  28.     <a target="_blank" href="<%=path%>/jsp/03.jsp">批量下载03</a>  
  29.   </body>  
  30. </html>  


01.jsp

[html] view plain copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  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>SmartUpload_批量上传</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"> 
  21.     -->  
  22.   
  23.   </head>  
  24.     
  25.   <body>  
  26.     <form action="<%=path%>/SmartUploadServlet.do" method="post" enctype="multipart/form-data">  
  27.         上传文件1:<input id="myfile1" name="myfile1" type="file"/><br>  
  28.         上传文件2:<input id="myfile2" name="myfile2" type="file"/><br>  
  29.         上传文件3:<input id="myfile3" name="myfile3" type="file"/>  
  30.         <input type="submit" value="提交"  />  ${result}  
  31.     </form>  
  32.   </body>  
  33. </html>  


02.jsp

[html] view plain copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE>  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP '02.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"> 
  21.     -->  
  22.   
  23.   </head>  
  24.     
  25.   <body>  
  26.     下载:<a href="<%=path %>/SmartDownloadServlet.do?filename=jplin-css.jpg">文件</a>  ${result}  
  27.   </body>  
  28. </html>  


03.jsp

[html] view plain copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE>  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>批量下载</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"> 
  21.     -->  
  22.   
  23.   </head>  
  24.     
  25.   <body>  
  26.         <h3>批量下载</h3>  
  27.         <form action="<%=path %>/BatchSmartDownloadServlet.do" method="post">  
  28.             <input type="checkbox" name="filename" value="jplugin-css.jpg"/>jplugin-css.jpg<br>  
  29.             <input type="checkbox" name="filename" value="jplugin-multiple.jpg"/>jplugin-multiple.jpg<br>  
  30.             <input type="checkbox" name="filename" value="jplugin-nocss.jpg"/>jplugin-nocss.jpg<br>  
  31.               
  32.             <input type="submit" value="提交">  
  33.         </form>  
  34.           
  35.           
  36.   </body>  
  37. </html>