jspSmartUpload组件是一个可以免费使用的文件上传与下载组件。用户可以把他安装在web服务器上,再进行使用。
jspSmartUpload组件使用非常简单。在jsp文件中仅需要写几行代码就可以实现文件的上传、下载。并能够全程控制上传。利用jspSmartUpload|组件提供的对象及其操作方法,可以获得全部上传、下载的信息,如文件名,大小,类型、扩展名。。。。以方便文件的存取;能对上传的文件在大小、类型等方面做出限制。这样就可以过滤掉不符合要求的文件;下载灵活。只须写很少的代码就能把web服务器变成文件服务器,不管文件在不在web服务器的目录下,都可以利用该组件进行下载。
在使用jspSmartUpload时,必须将该组件放在项目中相应的目录里,如:WebRoot/WEB-INF/lib
一、文件上传
下面是一个jsp页面,表单中有4个文件输入文本框,可以同时上传4个文件:
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>
当然可以设置同时上传更多的文件......
servlet处理程序:
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 }
该程序直接使用SmartUploa对象来实现文件上传。在申请对象后,必须要对其进行初始化:smartUpload.initialize(this.getServletConfig(),request,response);
二、文件下载
使用jspSmartUpload组件进行文件下载,可以非常简单:
jsp页面:
1 <a href="${pageContext.request.contextPath }/file1?file=downByJsmart&name=user.txt">下载user</a>
处理程序:
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】
项目目录
web.xml配置
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="3.0"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
- <display-name></display-name>
- <servlet>
- <description>This is the description of my J2EE component</description>
- <display-name>This is the display name of my J2EE component</display-name>
- <servlet-name>SmartUploadServlet</servlet-name>
- <servlet-class>com.wuhn.smartupload.servlet.SmartUploadServlet</servlet-class>
- </servlet>
- <servlet>
- <description>This is the description of my J2EE component</description>
- <display-name>This is the display name of my J2EE component</display-name>
- <servlet-name>SmartDownloadServlet</servlet-name>
- <servlet-class>com.wuhn.smartupload.servlet.SmartDownloadServlet</servlet-class>
- </servlet>
- <servlet>
- <description>This is the description of my J2EE component</description>
- <display-name>This is the display name of my J2EE component</display-name>
- <servlet-name>BatchSmartDownloadServlet</servlet-name>
- <servlet-class>com.wuhn.smartupload.servlet.BatchSmartDownloadServlet</servlet-class>
- </servlet>
-
-
- <servlet-mapping>
- <servlet-name>SmartUploadServlet</servlet-name>
- <url-pattern>/SmartUploadServlet.do</url-pattern>
- </servlet-mapping>
-
- <servlet-mapping>
- <servlet-name>SmartDownloadServlet</servlet-name>
- <url-pattern>/SmartDownloadServlet.do</url-pattern>
- </servlet-mapping>
-
- <servlet-mapping>
- <servlet-name>BatchSmartDownloadServlet</servlet-name>
- <url-pattern>/BatchSmartDownloadServlet.do</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
后台servlet
SmartUploadServlet.java
- package com.wuhn.smartupload.servlet;
-
- import java.io.File;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.sql.SQLException;
-
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- import com.jspsmart.upload.SmartUpload;
- import com.jspsmart.upload.SmartUploadException;
-
-
-
-
-
-
- public class SmartUploadServlet extends HttpServlet {
-
-
-
-
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doPost(request,response);
-
- }
-
-
-
-
-
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
-
- String filePath = getServletContext().getRealPath("/")+"images";
- File file = new File(filePath);
- if(!file.exists()){
- file.mkdir();
- }
-
- SmartUpload smartUpload = new SmartUpload();
-
- smartUpload.initialize(getServletConfig(), request, response);
-
- smartUpload.setMaxFileSize(1024*1024*10);
-
- smartUpload.setTotalMaxFileSize(1024*1024*100);
-
- smartUpload.setAllowedFilesList("txt,jpg,gif");
- String result = "上传成功!";
-
- try {
- smartUpload.setDeniedFilesList("rar,jsp,js");
-
- smartUpload.upload();
-
- int count = smartUpload.save(filePath);
- } catch (Exception e) {
-
- result = "上传失败!";
- if(e.getMessage().indexOf("1015") != -1){
- result = "上传失败:上传文件类型不正确!";
- }else if (e.getMessage().indexOf("1010") != -1) {
- result = "上传失败:上传文件类型不正确!";
- }else if (e.getMessage().indexOf("1105") != -1) {
- result = "上传失败:上传文件大小大于允许上传的最大值!";
- }else if (e.getMessage().indexOf("1110") != -1) {
- result = "上传失败:上传文件总大小大于允许上传总大小的最大值!";
- }
- e.printStackTrace();
- }
-
-
- for(int i=0;i<smartUpload.getFiles().getCount();i++){
- com.jspsmart.upload.File tempFile = smartUpload.getFiles().getFile(i);
- System.out.println("***************");
- System.out.println("表单中name的值:"+tempFile.getFileName());
- System.out.println("上传文件名:"+tempFile.getFileName());
- System.out.println("上传文件大小:"+tempFile.getSize());
- System.out.println("上传文件的拓展名:"+tempFile.getFileExt());
- System.out.println("上传文件全名:"+tempFile.getFilePathName());
- System.out.println("***************");
- }
-
- System.out.println("上传结果:"+result);
- request.setAttribute("result", result);
- request.getRequestDispatcher("/jsp/01.jsp").forward(request, response);
-
-
- }
-
- }
SmartDownloadServlet.java
- package com.wuhn.smartupload.servlet;
-
- import java.io.IOException;
- import java.io.PrintWriter;
-
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- import com.jspsmart.upload.SmartUpload;
- import com.jspsmart.upload.SmartUploadException;
-
-
-
-
-
-
- public class SmartDownloadServlet extends HttpServlet {
-
-
-
-
-
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doPost(request,response);
-
- }
-
-
-
-
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- String result = "下载成功";
-
- String filename = request.getParameter("filename");
-
- SmartUpload smartUpload = new SmartUpload();
- smartUpload.initialize(getServletConfig(), request, response);
- smartUpload.setContentDisposition(null);
- try {
- smartUpload.downloadFile("/images/"+filename);
- } catch (Exception e) {
- result = "下载失败";
- System.out.println("********异常处理********");
- if(e.getMessage().indexOf("系统找不到指定的路径。") != -1){
- result = "下载失败:文件不存在!";
- }
- e.printStackTrace();
- }
-
- request.setAttribute("result", result);
- request.getRequestDispatcher("/jsp/02.jsp").forward(request, response);
-
-
- }
-
- }
BatchSmartDownloadServlet.java
- package com.wuhn.smartupload.servlet;
-
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.Iterator;
- import java.util.zip.ZipEntry;
- import java.util.zip.ZipOutputStream;
-
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
-
-
-
-
-
- public class BatchSmartDownloadServlet extends HttpServlet {
-
-
-
-
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doPost(request,response);
-
- }
-
-
-
-
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
-
- response.setContentType("application/x-msdownload");
- response.setHeader("Content-Disposition", "attachment;filename=test.zip");
-
-
- String path = getServletContext().getRealPath("/")+"images/";
-
- String[] filenames = request.getParameterValues("filename");
- String str = "";
- String rt = "\r\n";
-
- ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());
-
- for(String filename:filenames){
- str += filename + rt;
- File file = new File(path + filename);
- zipOutputStream.putNextEntry(new ZipEntry(filename));
- FileInputStream fileInputStream = new FileInputStream(file);
- byte b[] = new byte[1024];
- int n=0;
- while ((n=fileInputStream.read(b)) != -1) {
- zipOutputStream.write(b, 0, n);
- }
- zipOutputStream.flush();
- fileInputStream.close();
- }
-
- zipOutputStream.setComment("download success:" + rt +str);
- zipOutputStream.flush();
- zipOutputStream.close();
-
-
- }
-
- }
前台页面jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE>
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'index.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
- </head>
-
- <body>
- <a target="_blank" href="<%=path%>/jsp/01.jsp">上传01</a>
- <br>
- <a target="_blank" href="<%=path%>/jsp/02.jsp">下载02</a>
- <br>
- <a target="_blank" href="<%=path%>/jsp/03.jsp">批量下载03</a>
- </body>
- </html>
01.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>SmartUpload_批量上传</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
-
- </head>
-
- <body>
- <form action="<%=path%>/SmartUploadServlet.do" method="post" enctype="multipart/form-data">
- 上传文件1:<input id="myfile1" name="myfile1" type="file"/><br>
- 上传文件2:<input id="myfile2" name="myfile2" type="file"/><br>
- 上传文件3:<input id="myfile3" name="myfile3" type="file"/>
- <input type="submit" value="提交" /> ${result}
- </form>
- </body>
- </html>
02.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE>
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP '02.jsp' starting page</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
-
- </head>
-
- <body>
- 下载:<a href="<%=path %>/SmartDownloadServlet.do?filename=jplin-css.jpg">文件</a> ${result}
- </body>
- </html>
03.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE>
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>批量下载</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
-
- </head>
-
- <body>
- <h3>批量下载</h3>
- <form action="<%=path %>/BatchSmartDownloadServlet.do" method="post">
- <input type="checkbox" name="filename" value="jplugin-css.jpg"/>jplugin-css.jpg<br>
- <input type="checkbox" name="filename" value="jplugin-multiple.jpg"/>jplugin-multiple.jpg<br>
- <input type="checkbox" name="filename" value="jplugin-nocss.jpg"/>jplugin-nocss.jpg<br>
-
- <input type="submit" value="提交">
- </form>
-
-
- </body>
- </html>