一个更方便使用的upload类

本文介绍了一个Java类,用于处理HTTP请求中的文件上传。通过继承HttpServletRequest接口,该类提供了额外的方法来解析multipart/form-data类型的请求数据,并能获取上传文件的名称、内容类型及内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package net.java2000.tools;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * <p>
 * Title: Java 程序
 * </p>
 * <p>
 * Description: 通用的请求处理程序,能够处理上传方式
 * </p>
 * 
 * <pre>
 *  一般使用方法如下
 *   &lt;%
 *   指定编码方式
 *   request.setCharacterEncoding(&quot;GBK&quot;);
 *   // 为文件上传做准备,该类读取接口与 request 相同
 *   net.java2000.tools.Upload upload = new net.java2000.tools.Upload(request);
 *   // 解析
 *   upload.parse();
 *   %&gt;
 *   ...
 *   &lt;%
 *   //使用标准方法读取参数
 *   String name = upload.getParameter(&quot;Name&quot;);
 *   String[] names = upload.getParameterValues(&quot;nameMultiSelected&quot;);
 *   &lt;br/&gt;
 *   // 读取上传信息,比如上传照片
 *   &lt;form method=&quot;POST&quot; name=&quot;form1&quot; enctype=&quot;multipart/form-data&quot; action=&quot;&quot; onsubmit=&quot;return check();&quot;&gt;
 *   &lt;input type=&quot;file&quot; name=&quot;photo&quot; size=&quot;8&quot; value=&quot;更新照片&quot;&gt;
 *   &lt;/form&gt;
 *   // 读取表单值,也就是照片的实际信息,请注意,该方法名包含Org,和前面的不同
 *   // 由于上传信息经常是二进制内容,所以不能采用编码后的字符串,应采用和流完全对应的字符串
 *   String photo = upload.getParameterOrg(&quot;photo&quot;);  // 此方法读取原始信息,没有进行任何编码,即ISO-8859-1 格式
 *   // 如果转化为字节数组为
 *   byte[] bytes = photo.getBytes(&quot;iso-8859-1&quot;);
 *   // 读取照片的类型
 *   String contentType = upload.getContentType(&quot;photo&quot;);
 *   // 读取照片文件名,不包含路径
 *   String filename = upload.getFilename(&quot;photo&quot;);
 *   %&gt;
 *   请在尽可能前的地方使用,特别是&lt;b&gt;不要&lt;/b&gt;再使用了
 *   request.getParameter(&quot;XXX&quot;);
 *   后面使用,因为这时候的输入流已经被系统使用了。
 * </pre>
 * 
 * <p>
 * Copyright: Copyright (c) 2002
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * 
@author 赵学庆
 * 
@version 1.0
 
*/

public class Upload implements HttpServletRequest {

  
private HttpServletRequest request = null;

  
public Upload(HttpServletRequest request) {
    
this.request = request;
  }


  
public Object getAttribute(String name) {
    
return request.getAttribute(name);
  }


  
public java.util.Enumeration getAttributeNames() {
    
return request.getAttributeNames();
  }


  
public java.lang.String getCharacterEncoding() {
    
return request.getCharacterEncoding();
  }


  
public void setCharacterEncoding(String env) throws java.io.UnsupportedEncodingException {
    request.setCharacterEncoding(env);
  }


  
public int getContentLength() {
    
return request.getContentLength();
  }


  
public int getLocalPort() {
    
return request.getLocalPort();
  }


  
public String getLocalAddr() {
    
return request.getLocalAddr();
  }


  
public String getLocalName() {
    
return request.getLocalName();
  }


  
public int getRemotePort() {
    
return request.getRemotePort();
  }


  
public java.lang.String getContentType() {
    
return request.getContentType();
  }


  
public ServletInputStream getInputStream() throws java.io.IOException {
    
return request.getInputStream();
  }


  
public java.util.Map getParameterMap() {
    
return request.getParameterMap();
  }


  
public java.lang.String getProtocol() {
    
return request.getProtocol();
  }


  
public java.lang.String getScheme() {
    
return request.getScheme();
  }


  
public java.lang.String getServerName() {
    
return request.getServerName();
  }


  
public int getServerPort() {
    
return request.getServerPort();
  }


  
public java.io.BufferedReader getReader() throws java.io.IOException {
    
return request.getReader();
  }


  
public java.lang.String getRemoteAddr() {
    
return request.getRemoteAddr();
  }


  
public java.lang.String getRemoteHost() {
    
return request.getRemoteHost();
  }


  
public void setAttribute(java.lang.String name, Object o) {
    request.setAttribute(name, o);
  }


  
public void removeAttribute(java.lang.String name) {
    request.removeAttribute(name);
  }


  
public java.util.Locale getLocale() {
    
return request.getLocale();
  }


  
public java.util.Enumeration getLocales() {
    
return request.getLocales();
  }


  
public boolean isSecure() {
    
return request.isSecure();
  }


  
public RequestDispatcher getRequestDispatcher(String path) {
    
return request.getRequestDispatcher(path);
  }


  
public java.lang.String getRealPath(String path) {
    
return request.getRealPath(path);
  }


  
public java.lang.String getAuthType() {
    
return request.getAuthType();
  }


  
public Cookie[] getCookies() {
    
return request.getCookies();
  }


  
public long getDateHeader(java.lang.String name) {
    
return request.getDateHeader(name);
  }


  
public java.lang.String getHeader(java.lang.String name) {
    
return request.getHeader(name);
  }


  
public java.util.Enumeration getHeaders(java.lang.String name) {
    
return request.getHeaders(name);
  }


  
public java.util.Enumeration getHeaderNames() {
    
return request.getHeaderNames();
  }


  
public int getIntHeader(java.lang.String name) {
    
return request.getIntHeader(name);
  }


  
public java.lang.String getPathInfo() {
    
return request.getPathInfo();
  }


  
public java.lang.String getPathTranslated() {
    
return request.getPathTranslated();
  }


  
public java.lang.String getContextPath() {
    
return request.getContextPath();
  }


  
public java.lang.String getQueryString() {
    
return request.getQueryString();
  }


  
public java.lang.String getRemoteUser() {
    
return request.getRemoteUser();
  }


  
public boolean isUserInRole(java.lang.String role) {
    
return request.isUserInRole(role);
  }


  
public java.security.Principal getUserPrincipal() {
    
return request.getUserPrincipal();
  }


  
public java.lang.String getRequestedSessionId() {
    
return request.getRequestedSessionId();
  }


  
public java.lang.String getRequestURI() {
    
return request.getRequestURI();
  }


  
public java.lang.StringBuffer getRequestURL() {
    
return request.getRequestURL();
  }


  
public java.lang.String getServletPath() {
    
return request.getServletPath();
  }


  
public HttpSession getSession() {
    
return request.getSession();
  }


  
public HttpSession getSession(boolean create) {
    
return request.getSession(create);
  }


  
public boolean isRequestedSessionIdValid() {
    
return request.isRequestedSessionIdValid();
  }


  
public boolean isRequestedSessionIdFromCookie() {
    
return request.isRequestedSessionIdFromCookie();
  }


  
public boolean isRequestedSessionIdFromURL() {
    
return request.isRequestedSessionIdFromURL();
  }


  
public boolean isRequestedSessionIdFromUrl() {
    
return request.isRequestedSessionIdFromUrl();
  }


  
// 保存名字/对象对应关系
  private Hashtable uploadHash = new Hashtable();;

  
// 保存所有名字
  private Vector names = new Vector();;

  
// 分割标志
  private String splitsign = null;

  
// 结束标志
  private String endsign = null;

  
// 数据总长度
  private int totlelength = 0;

  
// 最大总容量,-1为不限制
  private int MAX = 1024 * 1024 * 100;

  
// 单个最大容量,-1为不限制
  private int MAX_SIMPLE = 1024 * 1024 * 50;

  
private boolean debug = false;

  
public void setDebug(boolean debug) {
    
this.debug = debug;
  }


  
public boolean isDebug() {
    
return this.debug;
  }


  
// 保存所有数据
  
// byte[] data;

  
/**
   * 设置总量的最大值
   * 
   * 
@param capacity 最大值,字节形式
   
*/

  
public void setMaxCapacity(int capacity) {
    
this.MAX = capacity;
    
if (MAX < MAX_SIMPLE) {
      MAX_SIMPLE 
= MAX;
    }

  }


  
/**
   * 取的总量的最大值
   * 
   * 
@return 最大值的字节形式
   
*/

  
public int getMaxCapacity() {
    
return this.MAX;
  }


  
/**
   * 设置单个的最大值
   * 
   * 
@param capacity 单个最大值
   
*/

  
public void setMaxCapacitySimple(int capacity) {
    
this.MAX_SIMPLE = capacity;
    
if (MAX < MAX_SIMPLE) {
      MAX 
= MAX_SIMPLE;
    }

  }


  
/**
   * 读取单个最大值
   * 
   * 
@return 单个最大值
   
*/

  
public int getMaxCapacitySimple() {
    
return this.MAX_SIMPLE;
  }


  
public static final int UPLOAD_OK = 0;

  
public static final int UPLOAD_UNKNOW_ERROR = -1;

  
public boolean isPost = false;

  
public int parse() {
    
return parse(this.request);
  }


  
/**
   * 解析输入流,生成需要的各种数值
   * 
   * 
@param request 输入流
   * 
@return 解析结果
   
*/

  
public int parse(HttpServletRequest request) {
    
this.request = request;
    
if (request.getMethod().equals("POST")) {
      isPost 
= true;
    }
 else {
      isPost 
= false;
      
return -1;
    }


    
// Content-Type: multipart/form-data;
    
// boundary=---------------------------7d5ea1c501bc
    
// Content-Type: application/x-www-form-urlencoded

    
// 本方法只处理 multipart/form-data
    String contentType = request.getContentType();
    
if (contentType == null || !contentType.startsWith("multipart/form-data")) {
      isPost 
= false;
      
return -1;
    }


    
try {

      
// 读取输入流
      ServletInputStream sis = request.getInputStream();

      
// 流的长度
      int len = request.getContentLength();

      
if ((MAX != -1&& (len > MAX)) {
        
return -1;
      }


      
// 保存一行数据
      byte[] b = new byte[65536];
      
int a = 0;
      
int k = 0;
      String s 
= "";

      
// 读取分割标志
      a = sis.readLine(b, 0, b.length);

      splitsign 
= new String(b, 0, a);

      
if (debug) {
        System.out.println(splitsign);
      }

      
// 结束标志
      endsign = new String(splitsign.substring(0, splitsign.length() - 2+ "-- ");

      
boolean isend;
      
do {
        _upload up 
= new _upload(splitsign, endsign, MAX_SIMPLE);

        
// 解析数据
        isend = up.parse(sis, this.debug);
        
if (up.name != null{

          
// 如果已经存在这个名字的对象,则进行重名处理
          if (names.contains(up.name)) {
            _upload upp 
= (_upload) uploadHash.get(up.name);

            
// 增加重名的对象
            upp.add(up.getUpload(0));

            up 
= null;
          }
 else {
            
// 保存名字对应关系
            uploadHash.put(up.name, up);

            
// 保存名字列表
            names.add(up.name);
          }

        }

      }
 while (!isend);
      
return UPLOAD_OK;
    }
 catch (Exception e) {
      
return UPLOAD_UNKNOW_ERROR;
    }

  }


  
public String getMethod() {
    
return isPost ? "POST" : "GET";
  }


  
public String getParameter(String name) {
    
if (!isPost) {
      
return request.getParameter(name);
    }

    String str 
= getParameterOrg(name);
    
if (str == null{
      
return str;
    }

    
try {
      
return new String(str.getBytes("iso-8859-1"), this.getCharacterEncoding());
    }
 catch (Exception e) {
      
return str;
    }

  }


  
public String getParameterOrg(String name) {
    
if (!isPost) {
      
return request.getParameter(name);
    }


    
return getParameterOrg(name, 0);
  }


  
public String getParameterOrg(String name, int index) {
    
if (name == null{
      
return null;
    }

    _upload up 
= (_upload) uploadHash.get(name);
    
if (up == null{
      
return null;
    }
 else {
      
return up.getValue(index);
    }

  }


  
public Enumeration getParameterNames() {
    
if (!isPost) {
      
return request.getParameterNames();
    }


    
return names.elements();
  }


  
public String[] getParameterValues(String name) {
    
if (!isPost) {
      
return request.getParameterValues(name);
    }


    
if (name == null{
      
return null;
    }

    _upload up 
= (_upload) uploadHash.get(name);
    
if (up == null{
      
return null;
    }
 else {
      
return up.getValues();
    }

  }


  
public String getFilename(String name) {
    
return getFilename(name, 0);
  }


  
public String getFilename(String name, int index) {
    
if (name == null{
      
return null;
    }

    _upload up 
= (_upload) uploadHash.get(name);
    
if (up == null{
      
return null;
    }
 else {
      
return up.getFilename(index);
    }

  }


  
public String getFullFilename(String name) {
    
return getFullFilename(name, 0);
  }


  
public String getFullFilename(String name, int index) {
    
if (name == null{
      
return null;
    }

    _upload up 
= (_upload) uploadHash.get(name);
    
if (up == null{
      
return null;
    }
 else {
      
return up.getFullFilename(index);
    }

  }


  
public String getContentType(String name) {
    
return getContentType(name, 0);
  }


  
public String getContentType(String name, int index) {
    
if (name == null{
      
return null;
    }

    _upload up 
= (_upload) uploadHash.get(name);
    
if (up == null{
      
return null;
    }
 else {
      
return up.getContentType(index);
    }

  }

}


class _upload {
  
// 名称
  String name = null;

  
// 保存名称和对象的关系
  Vector __uploadVector = null;

  
// 分割标志
  private String splitsign = null;

  
// 结束标志
  private String endsign = null;

  
// 单个最大容量,-1为不限制
  private int MAX_SIMPLE = -1;

  _upload(String splitsign, String endsign, 
int max_simple) {
    
this.splitsign = new String(splitsign);
    
this.endsign = new String(endsign);
    __uploadVector 
= new Vector();
    MAX_SIMPLE 
= max_simple;
  }


  
boolean parse(ServletInputStream sis, boolean debug) throws Exception {
    
// 类型
    String Content_Type = null;

    
// 数值
    String value = null;

    
// 文件名
    String filename = null;

    
// 保存数据的长度
    int filelength = 0;

    
// 保存一行数据
    byte[] b = new byte[65536];

    
int a = 0;
    
int k = 0;
    String s 
= "";

    
boolean isend = false;

    
// -------------------- 读取分段头信息 --------------------
    while (true{

      
// 读取一行
      a = sis.readLine(b, 0, b.length);

      s 
= new String(b, 0, a, "ISO-8859-1");

      
if (debug) {
        System.out.println(s);
      }

      
// s = new String(b,0,a);

      
// 判断是否为空行,如果是则跳出
      if (s.equals(""|| s.equals(" "|| s.equals(" "))
        
break;

      
// 查找名字
      if ((k = s.indexOf("name=")) != -1{
        s 
= s.substring(k + 6);
        k 
= s.indexOf(""");
        name 
= s.substring(0, k);
      }


      
// 查找文件名
      if ((k = s.indexOf("filename=")) != -1{
        s 
= s.substring(k + 10);
        k 
= s.indexOf(""");
        
if (k == -1{
          filename 
= s.substring(0);
        }
 else {
          filename 
= s.substring(0, k);
        }

      }


      
// 查找类型
      if ((k = s.indexOf("Content-Type: ")) != -1{
        Content_Type 
= s.substring(k + 14);
      }

    }


    
// -------------------- 开始读取内数据 --------------------
    StringBuffer buff = new StringBuffer();
    
boolean overflow = false;
    
while (true{

      
// 读取一行
      a = sis.readLine(b, 0, b.length);
      
if (a == -1)
        
break;
      s 
= new String(b, 0, a, "ISO-8859-1");

      
if (debug) {
        System.out.println(s);
      }

      
// s = new String(b,0,a);
      
// 是否到分割符/结束符
      if (s.equals(splitsign)) {
        
break;
      }
 else if (s.equals(endsign)) {
        isend 
= true;
        
break;
      }


      
// 限制单个数据的最大值
      buff.append(s);
      
if ((MAX_SIMPLE != -1&& (buff.length() > MAX_SIMPLE)) {
        buff.delete(MAX_SIMPLE, buff.length());
        overflow 
= true;
        
break;
      }

    }


    
// 去掉最后的换行回车
    if (!overflow && buff.length() >= 2{
      buff.setLength(buff.length() 
- 2);
    }


    value 
= buff.toString();

    
// 保存文件数据长度
    filelength = value.length();

    
// 保存解析的对象
    __upload __up = new __upload(name, Content_Type, value, filename);

    __uploadVector.add(__up);

    
return isend;
  }


  
/**
   * 增加一个重名的对象
   * 
   * 
@param _up 对象名
   
*/

  
void add(__upload _up) {
    __uploadVector.add(_up);
  }


  
/**
   * 得到对象
   * 
   * 
@param index 索引
   * 
@return 对象
   
*/

  __upload getUpload(
int index) {
    
if ((index >= 0&& (__uploadVector.size() > index)) {
      
return (__upload) __uploadVector.elementAt(index);
    }
 else {
      
return null;
    }

  }


  
/**
   * 读取值
   * 
   * 
@param index 索引
   * 
@return 第一个的值
   
*/

  String getValue(
int index) {
    __upload _up 
= getUpload(index);
    
if (_up == null{
      
return null;
    }
 else {
      
return _up.value;
    }

  }


  
/**
   * 读取文件名
   * 
   * 
@param index 索引
   * 
@return 文件名
   
*/

  String getFilename(
int index) {
    __upload _up 
= getUpload(index);
    
if (_up == null{
      
return null;
    }
 else {
      
return _up.filename;
    }

  }


  
/**
   * 读取文件长度
   * 
   * 
@param index 索引
   * 
@return 文件长度
   
*/

  
int getFileLength(int index) {
    __upload _up 
= getUpload(index);
    
if (_up == null{
      
return -1;
    }
 else if (_up.value == null{
      
return -1;
    }
 else {
      
return _up.value.length();
    }

  }


  
/**
   * 读取文件全名
   * 
   * 
@param index 索引
   * 
@return 文件全名
   
*/

  String getFullFilename(
int index) {
    __upload _up 
= getUpload(index);
    
if (_up == null{
      
return null;
    }
 else {
      
return _up.fullfilename;
    }

  }


  
/**
   * 读取第一个类型
   * 
   * 
@param index 索引
   * 
@return 第一个的类型
   
*/

  String getContentType(
int index) {
    __upload _up 
= getUpload(index);
    
if (_up == null{
      
return null;
    }
 else {
      
return _up.Content_Type;
    }

  }


  
/**
   * 读取所有的值
   * 
   * 
@return 值数组
   
*/

  String[] getValues() 
{
    Vector v 
= new Vector();
    
for (int i = 0; i < __uploadVector.size(); i++{

      v.add(((__upload) __uploadVector.elementAt(i)).value);
    }

    
return (String[]) v.toArray(new String[0]);
  }

}


class __upload {

  
// 名称
  String name = null;

  
// 类型
  String Content_Type = null;

  
// 数值
  String value = null;

  
// 文件名
  String filename = null;

  
// 文件全名
  String fullfilename = null;

  __upload(String name, String Content_Type, String value, String fullfilename) 
{
    
this.name = new String(name);
    
if (Content_Type != null)
      
this.Content_Type = new String(Content_Type.trim());
    
if (fullfilename != null{
      
this.fullfilename = new String(fullfilename.trim());

      
int index = fullfilename.lastIndexOf("/");
      
this.filename = fullfilename.substring(index + 1).trim();
    }

    
if (value != null)
      
this.value = value;
  }

}


 

 

使用方法

request.setCharacterEncoding("UTF-8"); 
  
// 为文件上传做准备,该类读取接口与 request 相同 
  net.java2000.tools.Upload upload = new net.java2000.tools.Upload(request); 
  upload.setCharacterEncoding(
"UTF-8"); 
  upload.setMaxCapacity(
10 * 1024 * 1024); 
  upload.setMaxCapacitySimple(
10 * 1024 * 1024); 
  
// 解析 
  upload.parse(); 
      // 读取普通参数
  String name 
= upload.getParameter("name"); // 普通读取参数,单选 
  String[] deleteaids = upload.getParameterValues("deleteaid[]"); // 读取多选普通参数 

  // 读取附件的方法 
  String pName= "myattachment_1"; 
  String filename = upload.getFilename(pName); // 读取文件名
  String fullFilename = upload.getFullFilename(pName); // 读取文件全名,包括路径
  String contentType = upload.getContentType(pName); 
  byte[] content = upload.getParameterOrg(pName).getBytes("iso-8859-1"); // 特殊的方法,对于二进制的内容,需要调用这个方法

  // 如果有重名的,则需要在调用方法后面加上顺序号,比如

  String filename2 = upload.getFilename(pName, 2); // 读取第二个附件的文件名
  String contentType2 = upload.getContentType(pName,2); 
  byte[] content2 = upload.getParameterOrg(pName,2).getBytes("iso-8859-1"); 

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值