一個(gè)更方便使用的upload類
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;
/** *//**
* * Title: Java 程序 * ** Description: 通用的請(qǐng)求處理程序,能夠處理上傳方式 * * ** 一般使用方法如下 * <% * 指定編碼方式 * request.setCharacterEncoding("GBK"); * // 為文件上傳做準(zhǔn)備,該類讀取接口與 request 相同 * net.java2000.tools.Upload upload = new net.java2000.tools.Upload(request); * // 解析 * upload.parse(); * %> * ... * <% * //使用標(biāo)準(zhǔn)方法讀取參數(shù) * String name = upload.getParameter("Name"); * String[] names = upload.getParameterValues("nameMultiSelected"); * <br/> * // 讀取上傳信息,比如上傳照片 * <form method="POST" name="form1" enctype="multipart/form-data" action="" onsubmit="return check();"> * <input type="file" name="photo" size="8" value="更新照片"> * </form> * // 讀取表單值,也就是照片的實(shí)際信息,請(qǐng)注意,該方法名包含Org,和前面的不同 * // 由于上傳信息經(jīng)常是二進(jìn)制內(nèi)容,所以不能采用編碼后的字符串,應(yīng)采用和流完全對(duì)應(yīng)的字符串 * String photo = upload.getParameterOrg("photo"); // 此方法讀取原始信息,沒有進(jìn)行任何編碼,即ISO-8859-1 格式 * // 如果轉(zhuǎn)化為字節(jié)數(shù)組為 * byte[] bytes = photo.getBytes("iso-8859-1"); * // 讀取照片的類型 * String contentType = upload.getContentType("photo"); * // 讀取照片文件名,不包含路徑 * String filename = upload.getFilename("photo"); * %> * 請(qǐng)?jiān)诒M可能前的地方使用,特別是<b>不要</b>再使用了 * request.getParameter("XXX"); * 后面使用,因?yàn)檫@時(shí)候的輸入流已經(jīng)被系統(tǒng)使用了。 ** * * Copyright: Copyright (c) 2002 * ** Company: * * * @author 趙學(xué)慶 * @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(); } // 保存名字/對(duì)象對(duì)應(yīng)關(guān)系 private Hashtable uploadHash = new Hashtable();; // 保存所有名字 private Vector names = new Vector();; // 分割標(biāo)志 private String splitsign = null; // 結(jié)束標(biāo)志 private String endsign = null; // 數(shù)據(jù)總長(zhǎng)度 private int totlelength = 0; // 最大總?cè)萘?-1為不限制 private int MAX = 1024 * 1024 * 100; // 單個(gè)最大容量,-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; } // 保存所有數(shù)據(jù) // byte[] data; /** *//** * 設(shè)置總量的最大值 * * @param capacity 最大值,字節(jié)形式 */ public void setMaxCapacity(int capacity) ...{ this.MAX = capacity; if (MAX < MAX_SIMPLE) ...{ MAX_SIMPLE = MAX; } } /** *//** * 取的總量的最大值 * * @return 最大值的字節(jié)形式 */ public int getMaxCapacity() ...{ return this.MAX; } /** *//** * 設(shè)置單個(gè)的最大值 * * @param capacity 單個(gè)最大值 */ public void setMaxCapacitySimple(int capacity) ...{ this.MAX_SIMPLE = capacity; if (MAX < MAX_SIMPLE) ...{ MAX = MAX_SIMPLE; } } /** *//** * 讀取單個(gè)最大值 * * @return 單個(gè)最大值 */ 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); } /** *//** * 解析輸入流,生成需要的各種數(shù)值 * * @param request 輸入流 * @return 解析結(jié)果 */ 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(); // 流的長(zhǎng)度 int len = request.getContentLength(); if ((MAX != -1) && (len > MAX)) ...{ return -1; } // 保存一行數(shù)據(jù) byte[] b = new byte[65536]; int a = 0; int k = 0; String s = ""; // 讀取分割標(biāo)志 a = sis.readLine(b, 0, b.length); splitsign = new String(b, 0, a); if (debug) ...{ System.out.println(splitsign); } // 結(jié)束標(biāo)志 endsign = new String(splitsign.substring(0, splitsign.length() - 2) + "-- "); boolean isend; do ...{ _upload up = new _upload(splitsign, endsign, MAX_SIMPLE); // 解析數(shù)據(jù) isend = up.parse(sis, this.debug); if (up.name != null) ...{ // 如果已經(jīng)存在這個(gè)名字的對(duì)象,則進(jìn)行重名處理 if (names.contains(up.name)) ...{ _upload upp = (_upload) uploadHash.get(up.name); // 增加重名的對(duì)象 upp.add(up.getUpload(0)); up = null; } else ...{ // 保存名字對(duì)應(yīng)關(guān)系 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; // 保存名稱和對(duì)象的關(guān)系 Vector __uploadVector = null; // 分割標(biāo)志 private String splitsign = null; // 結(jié)束標(biāo)志 private String endsign = null; // 單個(gè)最大容量,-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; // 數(shù)值 String value = null; // 文件名 String filename = null; // 保存數(shù)據(jù)的長(zhǎng)度 int filelength = 0; // 保存一行數(shù)據(jù) 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); } } // -------------------- 開始讀取內(nèi)數(shù)據(jù) -------------------- 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); // 是否到分割符/結(jié)束符 if (s.equals(splitsign)) ...{ break; } else if (s.equals(endsign)) ...{ isend = true; break; } // 限制單個(gè)數(shù)據(jù)的最大值 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(); // 保存文件數(shù)據(jù)長(zhǎng)度 filelength = value.length(); // 保存解析的對(duì)象 __upload __up = new __upload(name, Content_Type, value, filename); __uploadVector.add(__up); return isend; } /** *//** * 增加一個(gè)重名的對(duì)象 * * @param _up 對(duì)象名 */ void add(__upload _up) ...{ __uploadVector.add(_up); } /** *//** * 得到對(duì)象 * * @param index 索引 * @return 對(duì)象 */ __upload getUpload(int index) ...{ if ((index >= 0) && (__uploadVector.size() > index)) ...{ return (__upload) __uploadVector.elementAt(index); } else ...{ return null; } } /** *//** * 讀取值 * * @param index 索引 * @return 第一個(gè)的值 */ 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; } } /** *//** * 讀取文件長(zhǎng)度 * * @param index 索引 * @return 文件長(zhǎng)度 */ 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; } } /** *//** * 讀取第一個(gè)類型 * * @param index 索引 * @return 第一個(gè)的類型 */ String getContentType(int index) ...{ __upload _up = getUpload(index); if (_up == null) ...{ return null; } else ...{ return _up.Content_Type; } } /** *//** * 讀取所有的值 * * @return 值數(shù)組 */ 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; // 數(shù)值 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"); // 為文件上傳做準(zhǔn)備,該類讀取接口與 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(); // 讀取普通參數(shù) String name = upload.getParameter("name"); // 普通讀取參數(shù),單選 String[] deleteaids = upload.getParameterValues("deleteaid[]"); // 讀取多選普通參數(shù) // 讀取附件的方法 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"); // 特殊的方法,對(duì)于二進(jìn)制的內(nèi)容,需要調(diào)用這個(gè)方法 // 如果有重名的,則需要在調(diào)用方法后面加上順序號(hào),比如 String filename2 = upload.getFilename(pName, 2); // 讀取第二個(gè)附件的文件名 String contentType2 = upload.getContentType(pName,2); byte[] content2 = upload.getParameterOrg(pName,2).getBytes("iso-8859-1"); Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=2031158 |
|