---
title: "介绍两个jsp上传组件commons-fileupload和SmartUpload(部分来自网页)"
author: "ericjoe"
date: "2007-09-28T21:39:00Z"
tags: []
slug: "jsp-commons-fileupload-smartupload"
draft: false
lastmod: "2007-09-28T21:39:00Z"
id: 393848
url: "https://coffeef.iteye.com/blog/393848"
---

第1个上传组件commons-fileupload  
\=============commons-fileupload ================

common-fileupload组件是apache的一个开源项目之一，可以从[http://jakarta.apache.org/commons/fileupload/](http://jakarta.apache.org/commons/fileupload/)下载。该组件简单易用，可实现一次上传一个或多个文件，并可限制文件大小。  
\-下载后解压zip包，将commons-fileupload-1.1.1.jar,和commons-io-1.2.jar复制到tomcat的webapps\\你的webapp\\WEB-INF\\lib\\下，如果目录不存在请自建目录。  
新建一个servlet: FileUpload.java用于文件上传：  
package com.drp.util.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 org.apache.commons.fileupload.\*;  
import java.util.\*;  
import java.util.regex.\*;  
import java.io.\*;  
import org.apache.commons.fileupload.servlet.\*;  
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

public class FileUpload extends HttpServlet {

 private String uploadPath = ""; // 用于存放上传文件的目录  
   
 private File tempPath = new File("D:\\\\Tomcat 5.5\\\\webapps\\\\drp1.2\\\\tempimages\\\\"); // 用于存放临时文件的目录

 public void doPost(HttpServletRequest req, HttpServletResponse res)  
   throws ServletException, IOException {  
  res.setContentType("text/html; charset=GB18030");  
  PrintWriter out = res.getWriter();  
  System.out.println(req.getContentLength());  
  System.out.println(req.getContentType());  
  DiskFileItemFactory factory = new DiskFileItemFactory();  
  // maximum size that will be stored in memory  
  //允许设置内存中存储数据的门限，单位：字节  
  factory.setSizeThreshold(4096);  
  // the location for saving data that is larger than getSizeThreshold()  
  //如果文件大小大于SizeThreshold，则保存到临时目录  
  factory.setRepository(new File("D:\\\\Tomcat 5.5\\\\webapps\\\\drp1.2\\\\tempimages"));

  ServletFileUpload upload = new ServletFileUpload(factory);  
  // maximum size before a FileUploadException will be thrown  
  //最大上传文件，单位：字节  
  upload.setSizeMax(1000000);  
  try {  
   List fileItems = upload.parseRequest(req);  
   // assume we know there are two files. The first file is a small  
   // text file, the second is unknown and is written to a file on  
   // the server  
   Iterator iter = fileItems.iterator();

   // 正则匹配，过滤路径取文件名  
   String regExp = ".+\\\\\\\\(.+)$";

   // 过滤掉的文件类型  
   String\[] errorType = { ".exe", ".com", ".cgi", ".asp" };  
   Pattern p = Pattern.compile(regExp);  
   String itemNo = "";//文件存放路径  
   while (iter.hasNext()) {  
    FileItem item = (FileItem) iter.next();  
      
    // 忽略其他不是文件域的所有表单信息  
    if (!item.isFormField()) {  
     String name = item.getName();  
     long size = item.getSize();  
     if ((name == null || name.equals("")) && size == 0)  
      continue;  
     Matcher m = p.matcher(name);  
     boolean result = m.find();  
     if (result) {  
      for (int temp = 0; temp &lt; errorType.length; temp++) {  
       if (m.group(1).endsWith(errorType\[temp])) {  
        throw new IOException(name + ": wrong type");  
       }  
      }  
      try {

       // 保存上传的文件到指定的目录

       // 在下文中上传文件至数据库时，将对这里改写  
         item.write(new File("d:\\\\" + m.group(1)));

                                                          out.print(name+"&nbsp;&nbsp;"+size+"&lt;br&gt;");

      } catch (Exception e) {  
       out.println(e);  
      }

     } else {  
      throw new IOException("fail to upload");  
     }  
    }  
   }  
  } catch (IOException e) {  
   out.println(e);  
  } catch (FileUploadException e) {  
   out.println(e);  
  }  
 }

 public void init() throws ServletException {  
  this.uploadPath = this.getServletConfig().getInitParameter("upload\_path");//的到web.xml中的配置文件用于保存上传文件，也可以在已开始定义的时候初始化，不过这样可以通过改动配置文件来改动存放路径，不用该代码，增加了灵活性。  
 }  
}

web.xml中相应的配置如下：  
&lt;servlet&gt;  
   
        &lt;servlet-name&gt;FileUpload&lt;/servlet-name&gt;  
        &lt;servlet-class&gt;com.drp.util.servlet.FileUpload&lt;/servlet-class&gt;//注意路径

   &lt;init-param&gt;  
 &lt;param-name&gt;upload\_path&lt;/param-name&gt;  
 &lt;param-value&gt;D:\\\\Tomcat 5.5\\\\webapps\\\\drp1.2\\\\images\\\\item\\\\&lt;/param-value&gt;//存放地址   &lt;/init-param&gt;  
 &lt;/servlet&gt;

  &lt;servlet-mapping&gt;

    &lt;servlet-name&gt;FileUpload&lt;/servlet-name&gt;  
    &lt;url-pattern&gt;/servlet/FileUpload&lt;/url-pattern&gt;

 &lt;/servlet-mapping&gt;

对应的请求文件：

&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;  
&lt;html&gt;  
  &lt;head&gt;  
    &lt;title&gt;index.html&lt;/title&gt;

    &lt;meta http-equiv="keywords" content="keyword1,keyword2,keyword3"&gt;  
    &lt;meta http-equiv="description" content="this is my page"&gt;

    &lt;!--&lt;link rel="stylesheet" type="text/css" href="./styles.css"&gt;--&gt;

  &lt;/head&gt;

  &lt;body&gt;  
   //注意action地址，还有enctype要写成multipart/form-data，和method="POST"    &lt;form name="uploadform" method="POST" action="./servlet/FileUpload" ENCTYPE="multipart/form-data"&gt;

        &lt;table border="1" width="450" cellpadding="4" cellspacing="2" bordercolor="#9BD7FF"&gt;

        &lt;tr&gt;&lt;td width="100%" colspan="2"&gt;

                        文件1：&lt;input name="x" size="40" type="file"&gt;

        &lt;/td&gt;&lt;/tr&gt;

        &lt;tr&gt;&lt;td width="100%" colspan="2"&gt;

                        文件2：&lt;input name="y" size="40" type="file"&gt;

        &lt;/td&gt;&lt;/tr&gt;

        &lt;tr&gt;&lt;td width="100%" colspan="2"&gt;

                        文件3：&lt;input name="z" size="40" type="file"&gt;

        &lt;/td&gt;&lt;/tr&gt;

        &lt;/table&gt;

        &lt;br/&gt;&lt;br/&gt;

        &lt;table&gt;

        &lt;tr&gt;&lt;td align="center"&gt;&lt;input name="upload" type="submit" value="开始上传"/&gt;&lt;/td&gt;&lt;/tr&gt;

       &lt;/table&gt;

&lt;/form&gt;

  &lt;/body&gt;  
&lt;/html&gt;

第二个组件SmartUpload  
\=================SmartUpload=================================================  
SmartUpload.zip 下载地址： [http://dev2dev.bea.com.cn/bbs/servlet/D2DServlet/download/121-20468-118409-1176/SmartUpload.zip](http://dev2dev.bea.com.cn/bbs/servlet/D2DServlet/download/121-20468-118409-1176/SmartUpload.zip)  
解压后有6个主要文件：ServletUpload.java，SmartFile.java，SmartFiles.java，SmartRequest.java，SmartUpload.java，  SmartUploadException.java 将其放在你的javabeen目录下，注意每个文件的包名和你的存放位置是否相否，  
  由于不能传中文，根据网站上的介绍对其中的SmartUpload.java做修改添加toUtf8String(String s)方法：  
  改动后SmartUpload.java的全部代码如下：红色代表改动的部分：  
package com.drp.upload;//写你自己的包名

import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.sql.ResultSet;  
import java.sql.SQLException;  
import java.util.Vector;  
import javax.servlet.ServletConfig;  
import javax.servlet.ServletContext;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import javax.servlet.http.HttpSession;  
import javax.servlet.jsp.JspWriter;  
import javax.servlet.jsp.PageContext;

public class SmartUpload  
{  
    protected byte m\_binArray\[];  
    protected HttpServletRequest m\_request;  
    protected HttpServletResponse m\_response;  
    protected ServletContext m\_application;  
    private int m\_totalBytes;  
    private int m\_currentIndex;  
    private int m\_startData;  
    private int m\_endData;  
    private String m\_boundary;  
    private long m\_totalMaxFileSize;  
    private long m\_maxFileSize;  
    private Vector m\_deniedFilesList;  
    private Vector m\_allowedFilesList;  
    private boolean m\_denyPhysicalPath;

    //private boolean m\_forcePhysicalPath;  
    private String m\_contentDisposition;  
    public static final int SAVE\_AUTO = 0;  
    public static final int SAVE\_VIRTUAL = 1;  
    public static final int SAVE\_PHYSICAL = 2;  
    private SmartFiles m\_files;  
    private SmartRequest m\_formRequest;

    public SmartUpload()  
    {  
        m\_totalBytes = 0;  
        m\_currentIndex = 0;  
        m\_startData = 0;  
        m\_endData = 0;  
        m\_boundary = ""; //new String();  
        m\_totalMaxFileSize = 0L;  
        m\_maxFileSize = 0L;  
        m\_deniedFilesList = new Vector();  
        m\_allowedFilesList = new Vector();  
        m\_denyPhysicalPath = false;  
        //m\_forcePhysicalPath = false;  
        m\_contentDisposition = ""; //new String();  
        m\_files = new SmartFiles();  
        m\_formRequest = new SmartRequest();  
    }

    /\**  
     * @deprecated Method init is deprecated  
     \*/  
    public final void init(ServletConfig servletconfig) throws ServletException  
    {  
        m\_application = servletconfig.getServletContext();  
    }

    /\**  
     * @deprecated Method service is deprecated  
     \*/  
    public void service(HttpServletRequest httpservletrequest,HttpServletResponse httpservletresponse) throws

ServletException,IOException  
    {  
        m\_request = httpservletrequest;  
        m\_response = httpservletresponse;  
    }

    public final void initialize(ServletConfig servletconfig,HttpServletRequest

httpservletrequest,HttpServletResponse httpservletresponse) throws ServletException  
    {  
        m\_application = servletconfig.getServletContext();  
        m\_request = httpservletrequest;  
        m\_response = httpservletresponse;  
    }

    public final void initialize(PageContext pagecontext) throws ServletException  
    {  
        m\_application = pagecontext.getServletContext();  
        m\_request = (HttpServletRequest)pagecontext.getRequest();  
        m\_response = (HttpServletResponse)pagecontext.getResponse();  
    }

    /\**  
     * @deprecated Method initialize is deprecated  
     \*/  
    public final void initialize(ServletContext servletcontext,HttpSession httpsession,HttpServletRequest

httpservletrequest,HttpServletResponse httpservletresponse,JspWriter jspwriter) throws ServletException  
    {  
        m\_application = servletcontext;  
        m\_request = httpservletrequest;  
        m\_response = httpservletresponse;  
    }

    public void upload() throws ServletException,IOException,SmartUploadException  
    {  
        int i = 0;  
        //boolean flag = false;  
        boolean flag1 = false;  
        //boolean flag2 = false;  
        long l = 0L;  
        //String s = "";//new String();  
        //String s2 = "";//new String();  
        String s4 = ""; //new String();  
        String s5 = ""; //new String();  
        String s6 = ""; //new String();  
        String s7 = ""; //new String();  
        String s8 = ""; //new String();  
        String s9 = ""; //new String();  
        String s10 = ""; //new String();  
        m\_totalBytes = m\_request.getContentLength();  
        m\_binArray = new byte\[m\_totalBytes];  
        int j;  
        for(;i &lt; m\_totalBytes;i += j)  
        {  
            try  
            {  
                m\_request.getInputStream();  
                j = m\_request.getInputStream().read(m\_binArray,i,m\_totalBytes - i);  
            }  
            catch(Exception exception)  
            {  
                throw new SmartUploadException("Unable to upload.");  
            }  
        }

        for(;!flag1 && m\_currentIndex &lt; m\_totalBytes;m\_currentIndex++)  
        {  
            if(m\_binArray\[m\_currentIndex] == 13)  
            {  
                flag1 = true;  
            }  
            else  
            {  
                m\_boundary = m\_boundary + (char)m\_binArray\[m\_currentIndex];

            }  
        }  
        if(m\_currentIndex == 1)  
        {  
            return;  
        }  
        for(m\_currentIndex++;m\_currentIndex &lt; m\_totalBytes;m\_currentIndex = m\_currentIndex + 2)  
        {  
            String s1 = getDataHeader();  
            m\_currentIndex = m\_currentIndex + 2;  
            boolean flag3 = s1.indexOf("filename") &gt; 0;  
            String s3 = getDataFieldValue(s1,"name");  
            if(flag3)  
            {  
                s6 = getDataFieldValue(s1,"filename");  
                s4 = getFileName(s6);  
                s5 = getFileExt(s4);  
                s7 = getContentType(s1);  
                s8 = getContentDisp(s1);  
                s9 = getTypeMIME(s7);  
                s10 = getSubTypeMIME(s7);  
            }  
            getDataSection();  
            if(flag3 && s4.length() &gt; 0)  
            {  
                if(m\_deniedFilesList.contains(s5))  
                {  
                    throw new SecurityException("The extension of the file is denied to be uploaded (1015).");  
                }  
                if(!m\_allowedFilesList.isEmpty() && !m\_allowedFilesList.contains(s5))  
                {  
                    throw new SecurityException("The extension of the file is not allowed to be uploaded

(1010).");  
                }  
                if(m\_maxFileSize &gt; 0L && (long)((m\_endData - m\_startData) + 1) &gt; m\_maxFileSize)  
                {  
                    throw new SecurityException("Size exceeded for this file : " + s4 + " (1105).");  
                }  
                l += (m\_endData - m\_startData) + 1;  
                if(m\_totalMaxFileSize &gt; 0L && l &gt; m\_totalMaxFileSize)  
                {  
                    throw new SecurityException("Total File Size exceeded (1110).");  
                }  
            }  
            if(flag3)  
            {  
                SmartFile file = new SmartFile();  
                file.setParent(this);  
                file.setFieldName(s3);  
                file.setFileName(s4);  
                file.setFileExt(s5);  
                file.setFilePathName(s6);  
                file.setIsMissing(s6.length() == 0);  
                file.setContentType(s7);  
                file.setContentDisp(s8);  
                file.setTypeMIME(s9);  
                file.setSubTypeMIME(s10);  
                if(s7.indexOf("application/x-macbinary") &gt; 0)  
                {  
                    m\_startData = m\_startData + 128;  
                }  
                file.setSize((m\_endData - m\_startData) + 1);  
                file.setStartData(m\_startData);  
                file.setEndData(m\_endData);  
                m\_files.addFile(file);  
            }  
            else  
            {  
                String s11 = new String(m\_binArray,m\_startData,(m\_endData - m\_startData) + 1);  
                m\_formRequest.putParameter(s3,s11);  
            }  
            if((char)m\_binArray\[m\_currentIndex + 1] == '-')  
            {  
                break;  
            }  
        }  
    }

    public int save(String s) throws ServletException,IOException,SmartUploadException  
    {  
        return save(s,0);  
    }

    public int save(String s,int i) throws ServletException,IOException,SmartUploadException  
    {  
        int j = 0;  
        if(s == null)  
        {  
            s = m\_application.getRealPath("/");  
            //System.out.println("s == null,m\_application.getRealPath:" + s);  
        }  
        if(s.indexOf("/") != -1)  
        {  
            if(s.charAt(s.length() - 1) != '/')  
            {  
                s = s + "/";  
                //System.out.println("m\_application.getRealPath::" + s);  
            }  
        }  
        else  
        {  
            if(s.charAt(s.length() - 1) != '\\\\')  
            {  
                s = s + "\\\\";  
                //System.out.println("m\_application.getRealPath" + s);  
            }  
        }  
        //System.out.println("m\_application.getRealPath:::" + s);  
        FileNames = new String\[m\_files.getCount()];  
        for(int k = 0;k &lt; m\_files.getCount();k++)  
        {  
            if(!m\_files.getFile(k).isMissing())  
            {  
                //System.out.println("s + m\_files.getFile(k).getFileName():" + s + m\_files.getFile

(k).getFileName());  
                m\_files.getFile(k).saveAs(s + m\_files.getFile(k).getFileName(),i);  
                FileNames\[j] = s + m\_files.getFile(k).getFileName();  
                j++;  
            }  
        }

        return j;  
    }

    //Add  
    private String\[] FileNames;  
    public String\[] getFileNames()  
    {  
        //Method may expose internal representation by returning array  
        //Returning an array value stored in one of the object's fields exposes the internal representation of

the object.? For classes shared by other untrusted classes, this could potentially be a security issue.?

Returning a new copy of the array is better approach in many situations.  
        String\[] vFileNames = new String\[FileNames.length];  
        System.arraycopy(FileNames,0,vFileNames,0,FileNames.length);  
        return vFileNames;  
    }

    public int getSize()  
    {  
        return m\_totalBytes;  
    }

    public byte getBinaryData(int i)  
    {  
        byte byte0;  
        try  
        {  
            byte0 = m\_binArray\[i];  
        }  
        catch(Exception exception)  
        {  
            throw new ArrayIndexOutOfBoundsException("Index out of range (1005).");  
        }  
        return byte0;  
    }

    public SmartFiles getFiles()  
    {  
        return m\_files;  
    }

    public SmartRequest getRequest()  
    {  
        return m\_formRequest;  
    }

    public void downloadFile(String s) throws ServletException,IOException,SmartUploadException  
    {  
        downloadFile(s,null,null);  
    }

 

    public void downloadFile(String s,String s1) throws

ServletException,IOException,SmartUploadException,SmartUploadException  
    {  
        downloadFile(s,s1,null);  
    }

    public void downloadFile(String s,String s1,String s2) throws

ServletException,IOException,SmartUploadException  
    {  
        downloadFile(s,s1,s2,65000);  
    }

   public void downloadFile(String s, String s1, String s2, int i)  
 throws ServletException, IOException, SmartUploadException  
    {  
 if(s == null)  
     throw new IllegalArgumentException("File '" + s +  
     "' not found (1040).");  
 if(s.equals(""))  
     throw new IllegalArgumentException("File '" + s +  
     "' not found (1040).");  
 if(!isVirtual(s) && m\_denyPhysicalPath)  
     throw new SecurityException("Physical path is denied (1035).");  
 if(isVirtual(s))  
     s = m\_application.getRealPath(s);  
 java.io.File file = new java.io.File(s);  
 FileInputStream fileinputstream = new FileInputStream(file);  
 long l = file.length();  
 boolean flag = false;  
 int k = 0;  
 byte abyte0\[] = new byte\[i];  
 if(s1 == null)  
     m\_response.setContentType("application/x-msdownload");  
 else  
 if(s1.length() == 0)  
     m\_response.setContentType("application/x-msdownload");  
 else  
     m\_response.setContentType(s1);  
 m\_response.setContentLength((int)l);  
 m\_contentDisposition = m\_contentDisposition != null ?  
 m\_contentDisposition : "attachment;";  
 if(s2 == null)  
     m\_response.setHeader("Content-Disposition",  
     m\_contentDisposition + " filename=" +  
     toUtf8String(getFileName(s)));  
 else  
 if(s2.length() == 0)  
     m\_response.setHeader("Content-Disposition",  
     m\_contentDisposition);  
 else  
     m\_response.setHeader("Content-Disposition", 

     m\_contentDisposition + " filename=" + toUtf8String(s2));

 while((long)k &lt; l)  
 {  
     int j = fileinputstream.read(abyte0, 0, i);  
     k += j;  
     m\_response.getOutputStream().write(abyte0, 0, j);  
 }  
 fileinputstream.close();  
    }

 public static String toUtf8String(String s) {  
 StringBuffer sb = new StringBuffer();  
 for (int i=0;i&lt;s.length();i++) {  
     char c = s.charAt(i);  
     if (c &gt;= 0 && c &lt;= 255) {  
  sb.append(c);  
     } else {  
  byte\[] b;  
  try {  
      b = Character.toString(c).getBytes("utf-8");  
  } catch (Exception ex) {  
      System.out.println(ex);  
      b = new byte\[0];  
  }  
  for (int j = 0; j &lt; b.length; j++) {  
      int k = b\[j];  
      if (k &lt; 0) k += 256;  
      sb.append("%" + Integer.toHexString(k).  
      toUpperCase());  
  }  
     }  
 }  
 return sb.toString();  
    }  
    public void downloadField(ResultSet resultset,String s,String s1,String s2) throws

ServletException,IOException,SQLException  
    {  
        if(resultset == null)  
        {  
            throw new IllegalArgumentException("The RecordSet cannot be null (1045).");  
        }  
        if(s == null)  
        {  
            throw new IllegalArgumentException("The columnName cannot be null (1050).");  
        }  
        if(s.length() == 0)  
        {  
            throw new IllegalArgumentException("The columnName cannot be empty (1055).");  
        }  
        byte abyte0\[] = resultset.getBytes(s);  
        if(s1 == null)  
        {  
            m\_response.setContentType("application/x-msdownload");  
        }  
        else  
        {  
            if(s1.length() == 0)  
            {  
                m\_response.setContentType("application/x-msdownload");  
            }  
            else  
            {  
                m\_response.setContentType(s1);  
            }  
        }  
        m\_response.setContentLength(abyte0.length);  
        if(s2 == null)  
        {  
            m\_response.setHeader("Content-Disposition","attachment;");  
        }  
        else  
        {  
            if(s2.length() == 0)  
            {  
                m\_response.setHeader("Content-Disposition","attachment;");  
            }  
            else  
            {  
                m\_response.setHeader("Content-Disposition","attachment; filename=" + s2);  
            }  
        }  
        m\_response.getOutputStream().write(abyte0,0,abyte0.length);  
    }

 

    public void fieldToFile(ResultSet resultset,String s,String s1) throws

ServletException,IOException,SmartUploadException,SQLException  
    {  
        try  
        {  
            if(m\_application.getRealPath(s1) != null)  
            {  
                s1 = m\_application.getRealPath(s1);  
            }  
            InputStream inputstream = resultset.getBinaryStream(s);  
            FileOutputStream fileoutputstream = new FileOutputStream(s1);  
            int i;  
            while((i = inputstream.read()) != -1)  
            {  
                fileoutputstream.write(i);  
            }  
            fileoutputstream.close();  
        }  
        catch(Exception exception)  
        {  
            throw new SmartUploadException("Unable to save file from the DataBase (1020).");  
        }  
    }

    private String getDataFieldValue(String s,String s1)  
    {  
        String s2 = ""; // = new String();  
        String s3 = ""; // = new String();  
        int i = 0;  
        //boolean flag = false;  
        //boolean flag1 = false;  
        //boolean flag2 = false;  
        s2 = s1 + "=" + '"';  
        i = s.indexOf(s2);  
        if(i &gt; 0)  
        {  
            int j = i + s2.length();  
            int k = j;  
            s2 = "\\"";  
            int l = s.indexOf(s2,j);  
            if(k &gt; 0 && l &gt; 0)  
            {  
                s3 = s.substring(k,l);  
            }  
        }  
        return s3;  
    }

    private String getFileExt(String s)  
    {  
        String s1; // = new String();  
        int i = 0;  
        int j = 0;  
        if(s == null)  
        {  
            return null;  
        }  
        i = s.lastIndexOf('.') + 1;  
        j = s.length();  
        s1 = s.substring(i,j);  
        if(s.lastIndexOf('.') &gt; 0)  
        {  
            return s1;  
        }  
        else  
        {  
            return "";  
        }  
    }

    private String getContentType(String s)  
    {  
        String s1 = ""; // = new String();  
        String s2 = ""; // = new String();  
        int i = 0;  
        //boolean flag = false;  
        s1 = "Content-Type:";  
        i = s.indexOf(s1) + s1.length();  
        if(i != -1)  
        {  
            int j = s.length();  
            s2 = s.substring(i,j);  
        }  
        return s2;  
    }

    private String getTypeMIME(String s)  
    {  
        //String s1 = new String();  
        int i = 0;  
        i = s.indexOf("/");  
        if(i != -1)  
        {  
            return s.substring(1,i);  
        }  
        else  
        {  
            return s;  
        }  
    }

    private String getSubTypeMIME(String s)  
    {  
        //String s1 = new String();  
        //boolean flag = false;  
        int i = 0;  
        i = s.indexOf("/") + 1;  
        if(i != -1)  
        {  
            int j = s.length();  
            return s.substring(i,j);  
        }  
        else  
        {  
            return s;  
        }  
    }

    private String getContentDisp(String s)  
    {  
        //String s1 = new String();  
        String s1 = "";  
        int i = 0;  
        int j = 0;  
        i = s.indexOf(":") + 1;  
        j = s.indexOf(";");  
        s1 = s.substring(i,j);  
        return s1;  
    }

    private void getDataSection()  
    {  
        //boolean flag = false;  
        //String s = "";  
        //String s = new String();  
        int i = m\_currentIndex;  
        int j = 0;  
        int k = m\_boundary.length();  
        m\_startData = m\_currentIndex;  
        m\_endData = 0;  
        while(i &lt; m\_totalBytes)  
        {  
            if(m\_binArray\[i] == (byte)m\_boundary.charAt(j))  
            {  
                if(j == k - 1)  
                {  
                    m\_endData = ((i - k) + 1) - 3;  
                    break;  
                }  
                i++;  
                j++;  
            }  
            else  
            {  
                i++;  
                j = 0;  
            }  
        }  
        m\_currentIndex = m\_endData + k + 3;  
    }

    private String getDataHeader()  
    {  
        //boolean flag = false;  
        int i = m\_currentIndex;  
        int j = 0;  
        for(boolean flag1 = false;!flag1;)  
        {  
            if(m\_binArray\[m\_currentIndex] == 13 && m\_binArray\[m\_currentIndex + 2] == 13)  
            {  
                flag1 = true;  
                j = m\_currentIndex - 1;  
                m\_currentIndex = m\_currentIndex + 2;  
            }  
            else  
            {  
                m\_currentIndex++;  
            }  
        }

        String s = new String(m\_binArray,i,(j - i) + 1);  
        return s;  
    }

    private String getFileName(String s)  
    {  
        //String s1 = ""; // = new String();  
        //String s2 = ""; // = new String();  
        //boolean flag = false;  
        //boolean flag1 = false;  
        //boolean flag2 = false;  
        int i = 0;  
        i = s.lastIndexOf('/');  
        if(i != -1)  
        {  
            return s.substring(i + 1,s.length());  
        }  
        i = s.lastIndexOf('\\\\');  
        if(i != -1)  
        {  
            return s.substring(i + 1,s.length());  
        }  
        else  
        {  
            return s;  
        }  
    }

    public void setDeniedFilesList(String s) throws ServletException,IOException,SQLException  
    {  
        //String s1 = "";  
        if(s != null)  
        {  
            String s2 = "";  
            for(int i = 0;i &lt; s.length();i++)  
            {  
                if(s.charAt(i) == ',')  
                {  
                    if(!m\_deniedFilesList.contains(s2))  
                    {  
                        m\_deniedFilesList.addElement(s2);  
                    }  
                    s2 = "";  
                }  
                else  
                {  
                    s2 = s2 + s.charAt(i);  
                }  
            }

            //if(s2 != "")  
            if(!s2.equals(""))  
            {  
                m\_deniedFilesList.addElement(s2);  
            }  
        }  
        else  
        {  
            m\_deniedFilesList = null;  
        }  
    }

    public void setAllowedFilesList(String s)  
    {  
        //String s1 = "";  
        if(s != null)  
        {  
            String s2 = "";  
            for(int i = 0;i &lt; s.length();i++)  
            {  
                if(s.charAt(i) == ',')  
                {  
                    if(!m\_allowedFilesList.contains(s2))  
                    {  
                        m\_allowedFilesList.addElement(s2);  
                    }  
                    s2 = "";  
                }  
                else  
                {  
                    s2 = s2 + s.charAt(i);  
                }  
            }  
            //if(s2 != "")  
            if(!s2.equals(""))  
            {  
                m\_allowedFilesList.addElement(s2);  
            }  
        }  
        else  
        {  
            m\_allowedFilesList = null;  
        }  
    }

    public void setDenyPhysicalPath(boolean flag)  
    {  
        m\_denyPhysicalPath = flag;  
    }

    public void setForcePhysicalPath(boolean flag)  
    {  
        //m\_forcePhysicalPath = flag;  
    }

    public void setContentDisposition(String s)  
    {  
        m\_contentDisposition = s;  
    }

    public void setTotalMaxFileSize(long l)  
    {  
        m\_totalMaxFileSize = l;  
    }

    public void setMaxFileSize(long l)  
    {  
        m\_maxFileSize = l;  
    }

    protected String getPhysicalPath(String s,int i) throws IOException  
    {  
        String s1 = ""; //new String();  
        String s2 = ""; //new String();  
        String s3 = ""; //new String();  
        boolean flag = false;  
        s3 = System.getProperty("file.separator");  
        if(s == null)  
        {  
            throw new IllegalArgumentException("There is no specified destination file (1140).");  
        }  
        if(s.equals(""))  
        {  
            throw new IllegalArgumentException("There is no specified destination file (1140).");  
        }  
        if(s.lastIndexOf("\\\\") &gt;= 0)  
        {  
            s1 = s.substring(0,s.lastIndexOf("\\\\"));  
            s2 = s.substring(s.lastIndexOf("\\\\") + 1);  
        }  
        if(s.lastIndexOf("/") &gt;= 0)  
        {  
            s1 = s.substring(0,s.lastIndexOf("/"));  
            s2 = s.substring(s.lastIndexOf("/") + 1);  
        }  
        s1 = s1.length() != 0 ? s1 : "/";  
        java.io.File file = new java.io.File(s1);  
        if(file.exists())  
        {  
            flag = true;  
        }  
        if(i == 0)  
        {  
            if(isVirtual(s1))  
            {  
                s1 = m\_application.getRealPath(s1);  
                if(s1.endsWith(s3))  
                {  
                    s1 = s1 + s2;  
                }  
                else  
                {  
                    s1 = s1 + s3 + s2;  
                }  
                return s1;  
            }  
            if(flag)  
            {  
                if(m\_denyPhysicalPath)  
                {  
                    throw new IllegalArgumentException("Physical path is denied (1125).");  
                }  
                else  
                {  
                    return s;  
                }  
            }  
            else  
            {  
                throw new IllegalArgumentException("This path does not exist (1135).");  
            }  
        }  
        if(i == 1)  
        {  
            if(isVirtual(s1))  
            {  
                s1 = m\_application.getRealPath(s1);  
                if(s1.endsWith(s3))  
                {  
                    s1 = s1 + s2;  
                }  
                else  
                {  
                    s1 = s1 + s3 + s2;  
                }  
                return s1;  
            }  
            if(flag)  
            {  
                throw new IllegalArgumentException("The path is not a virtual path.");  
            }  
            else  
            {  
                throw new IllegalArgumentException("This path does not exist (1135).");  
            }  
        }  
        if(i == 2)  
        {  
            if(flag)  
            {  
                if(m\_denyPhysicalPath)  
                {  
                    throw new IllegalArgumentException("Physical path is denied (1125).");  
                }  
                else  
                {  
                    return s;  
                }  
            }  
            if(isVirtual(s1))  
            {  
                throw new IllegalArgumentException("The path is not a physical path.");  
            }  
            else  
            {  
                throw new IllegalArgumentException("This path does not exist (1135).");  
            }  
        }  
        else  
        {  
            return null;  
        }  
    }

    public void uploadInFile(String s) throws IOException,SmartUploadException  
    {  
        //boolean flag = false;  
        int i = 0;  
        int j = 0;  
        if(s == null)  
        {  
            throw new IllegalArgumentException("There is no specified destination file (1025).");  
        }  
        if(s.length() == 0)  
        {  
            throw new IllegalArgumentException("There is no specified destination file (1025).");  
        }  
        if(!isVirtual(s) && m\_denyPhysicalPath)  
        {  
            throw new SecurityException("Physical path is denied (1035).");  
        }  
        i = m\_request.getContentLength();  
        m\_binArray = new byte\[i];  
        int k;  
        for(;j &lt; i;j += k)  
        {  
            try  
            {  
                k = m\_request.getInputStream().read(m\_binArray,j,i - j);  
            }  
            catch(Exception exception)  
            {  
                throw new SmartUploadException("Unable to upload.");  
            }  
        }

        if(isVirtual(s))  
        {  
            s = m\_application.getRealPath(s);  
        }  
        try  
        {  
            java.io.File file = new java.io.File(s);  
            FileOutputStream fileoutputstream = new FileOutputStream(file);  
            fileoutputstream.write(m\_binArray);  
            fileoutputstream.close();  
        }  
        catch(Exception exception1)  
        {  
            throw new SmartUploadException("The Form cannot be saved in the specified file (1030).");  
        }  
    }

    private boolean isVirtual(String s)  
    {  
        if(m\_application.getRealPath(s) != null)  
        {  
            java.io.File file = new java.io.File(m\_application.getRealPath(s));  
            return file.exists();  
        }  
        else  
        {  
            return false;  
        }  
    }

}

下面是上传的应用：  
首先是一个请求页面：  
upload.html

&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;  
&lt;html&gt;  
&lt;head&gt;  
&lt;title&gt;文件上传&lt;/title&gt;  
&lt;meta http-equiv="Content-Type" content="text/html; charset=gb2312"&gt;  
&lt;/head&gt;

&lt;body&gt;  
&lt;p&gt;&nbsp;&lt;/p&gt;  
&lt;p align="center"&gt;上传资源&lt;/p&gt;  
&lt;FORM METHOD="POST" ACTION="do\_upload.jsp"  
ENCTYPE="multipart/form-data"&gt;  
  &lt;table width="75%" border="1" align="center"&gt;  
    &lt;tr&gt;  
      &lt;td&gt;&lt;div align="center"&gt;1、  
          &lt;input type="FILE" name="FILE1" size="30"&gt;  
        &lt;/div&gt;&lt;/td&gt;  
    &lt;/tr&gt;  
      &lt;td&gt;&lt;div align="center"&gt;  
          &lt;input type="submit" name="Submit" value="上传"&gt;  
        &lt;/div&gt;&lt;/td&gt;  
    &lt;/tr&gt;  
  &lt;/table&gt;  
&lt;/FORM&gt;  
&lt;/body&gt;  
&lt;/html&gt;  
然后是处理页面：do\_upload.jsp

&lt;%@ page contentType="text/html; charset=gb2312" language="java"  
import="java.util.\*,com.drp.upload.\*" errorPage="" %&gt;//注意包名  
&lt;html&gt;  
&lt;head&gt;  
&lt;title&gt;文件上传处理页面&lt;/title&gt;  
&lt;meta http-equiv="Content-Type" content="text/html; charset=gb2312"&gt;  
&lt;/head&gt;

&lt;body&gt;  
&lt;%  
 // 新建一个SmartUpload对象  
 SmartUpload su = new SmartUpload();  
 // 上传初始化  
 su.initialize(pageContext);  
 // 设定上传限制  
 // 1.限制每个上传文件的最大长度。  
 // su.setMaxFileSize(10000);  
 // 2.限制总上传数据的长度。  
 // su.setTotalMaxFileSize(20000);  
 // 3.设定允许上传的文件（通过扩展名限制）,仅允许doc,txt文件。  
 // su.setAllowedFilesList("doc,txt");  
 // 4.设定禁止上传的文件（通过扩展名限制）,禁止上传带有exe,bat,  
 //jsp,htm,html扩展名的文件和没有扩展名的文件。  
 // su.setDeniedFilesList("exe,bat,jsp,htm,html");  
 // 上传文件  
 su.upload();  
 // 将上传文件全部保存到指定目录  
 int count = su.save("/upload");  
 out.println(count+"个文件上传成功！&lt;br&gt;");  
   
 

 // 逐一提取上传文件信息，同时可保存文件。  
 for (int i=0;i&lt;su.getFiles().getCount();i++)  
 {  
  SmartFile file = su.getFiles().getFile(i);  
    
  // 若文件不存在则继续  
  if (file.isMissing()) continue;

  // 显示当前文件信息  
  out.println("&lt;TABLE BORDER=1&gt;");  
  out.println("&lt;TR&gt;&lt;TD&gt;表单项名（FieldName）&lt;/TD&gt;&lt;TD&gt;"  
  + file.getFieldName() + "&lt;/TD&gt;&lt;/TR&gt;");  
  out.println("&lt;TR&gt;&lt;TD&gt;文件长度（Size）&lt;/TD&gt;&lt;TD&gt;" +  
  file.getSize() + "&lt;/TD&gt;&lt;/TR&gt;");  
  out.println("&lt;TR&gt;&lt;TD&gt;文件名（FileName）&lt;/TD&gt;&lt;TD&gt;"  
  + file.getFileName() + "&lt;/TD&gt;&lt;/TR&gt;");  
  out.println("&lt;TR&gt;&lt;TD&gt;文件扩展名（FileExt）&lt;/TD&gt;&lt;TD&gt;"  
  + file.getFileExt() + "&lt;/TD&gt;&lt;/TR&gt;");  
  out.println("&lt;TR&gt;&lt;TD&gt;文件全名（FilePathName）&lt;/TD&gt;&lt;TD&gt;"  
  + file.getFilePathName() + "&lt;/TD&gt;&lt;/TR&gt;");  
  out.println("&lt;/TABLE&gt;&lt;BR&gt;");

  // 将文件另存  
  // file.saveAs("/upload/" + myFile.getFileName());  
  // 另存到以WEB应用程序的根目录为文件根目录的目录下  
  // file.saveAs("/upload/" + myFile.getFileName(),  
    //su.SAVE\_VIRTUAL);  
  // 另存到操作系统的根目录为文件根目录的目录下  
  // file.saveAs("c:\\\\temp\\\\" + myFile.getFileName(),  
  //su.SAVE\_PHYSICAL);

 }  
%&gt;  
&lt;/body&gt;  
&lt;/html&gt;

下载：  
请求页面：download.html

&lt;html&gt;  
&lt;head&gt;  
&lt;title&gt;下载&lt;/title&gt;  
&lt;meta http-equiv="Content-Type" content="text/html; charset=gb2312"&gt;  
&lt;/head&gt;  
&lt;body&gt;  
&lt;form action="do\_download.jsp" method="post" name="form1" &gt;  
  &lt;table width="400" border="1" align="center"&gt;  
    &lt;tr&gt;  
      &lt;td&gt;&lt;div align="center"&gt;文件下载&lt;/div&gt;&lt;/td&gt;  
    &lt;/tr&gt;  
    &lt;tr&gt;  
      &lt;td&gt;&lt;div align="center"&gt;选择文件：  
          &lt;input name="file" type="file" size="25"&gt;  
      &lt;/div&gt;&lt;/td&gt;  
    &lt;/tr&gt;  
    &lt;tr&gt;  
      &lt;td&gt;&lt;div align="center"&gt;  
        &lt;input type="submit" name="Submit" value="提交"&gt;  
        &lt;input type="reset" name="Submit" value="重置"&gt;  
      &lt;/div&gt;&lt;/td&gt;  
    &lt;/tr&gt;  
  &lt;/table&gt;  
&lt;/form&gt;  
&lt;/body&gt;  
&lt;/html&gt;  
处理页面：do\_download.jsp  
&lt;%@ page language="java" contentType="text/html; charset=gbk" import="java.util.\*,com.drp.upload.\*"  
  pageEncoding="gbk"%&gt;  
&lt;% request.setCharacterEncoding("gbk"); %&gt;  
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;  
&lt;meta http-equiv="Content-Type" content="text/html; charset=gbk"&gt;  
&lt;title&gt;Insert title here&lt;/title&gt;

&lt;%  
response.setCharacterEncoding("gbk");  
String finame = request.getParameter("file");  
  // 新建一个SmartUpload对象  
 SmartUpload su = new SmartUpload();  
  // 初始化  
 su.initialize(pageContext);  
  // 设定contentDisposition为null以禁止浏览器自动打开文件，  
  //保证点击链接后是下载文件。若不设定，则下载的文件扩展名为  
  //doc时，浏览器将自动用word打开它。扩展名为pdf时，  
  //浏览器将用acrobat打开。  
 su.setContentDisposition(null);  
  // 下载文件  
 su.downloadFile(finame);

%&gt;