multiparse.java

来自「一个日本流行的,功能较全的开源Web办公管理(Groupware)系统。」· Java 代码 · 共 357 行

JAVA
357
字号
package jp.co.sjts.gsession.tools;


import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Hashtable;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>儅儖僠僷乕僗僋儔僗  MultiParse.java
 * <p>Copyright (C) 1999-2000 Japan Total System Co,LTD
 *
 * @author   Satoru K   &lt;koni@sjts.co.jp&gt;
 */
public class MultiParse {
	private HttpServletRequest req = null;
	private HttpServletResponse res = null;
	private ServletInputStream sis=null;

	private ByteArrayOutputStream byteArray;
	private byte[] bytes = new byte[8 * 1024];

	private boolean filepart;
	private String boundary=null;
	private Hashtable hash=null;

	private int maxSize = 0;

	public MultiParse(HttpServletRequest req,HttpServletResponse res) throws GSException {
		this(req,res,0);
	}

	public MultiParse(HttpServletRequest req,HttpServletResponse res,int maxsize) throws GSException {
		this.byteArray = new ByteArrayOutputStream();
		int idx = req.getContentType().indexOf("boundary=");
		if(idx == -1) // boundary 偑僙僢僩偝傟偰偄側偄丅
			throw new GSException("偙偺僽儔僂僓偱偼丄懳墳偟偰偍傝傑偣傫丅");

		String boundary = req.getContentType().substring(idx+9);
		if (boundary == null)
			throw new GSException("boundary 偑巜掕偝傟偰偄傑偣傫丅");

		this.boundary = "--" + boundary;
		this.maxSize = maxsize;
		this.req = req;
		this.res = res;
	}

	public Hashtable getHash() {
		return hash;
	}

	private StringBuffer readLine2() throws IOException {
		int result;
		int length=0;

		byteArray.reset();

		do {
			result = sis.readLine(bytes,0,bytes.length);
			if(result != -1) {
				length+=result;
				byteArray.write(bytes,0,result);
			}

		} while(result == bytes.length);

		if(length == 0)
			return null;

		return new StringBuffer(byteArray.toString("ISO-8859-1"));

	}

//  	public static String getHex(byte bArg) {
//  		int iArg=bArg;
//  		if(iArg<0) {
//  			iArg+=256;
//  		}
//  		return Integer.toHexString(iArg);
//  	}


	private String readLine() throws IOException {
		StringBuffer sb = readLine2();
		if(sb == null)
			return null;
		sb.setLength(sb.length()-2); // \r\n傪嶍彍
		return sb.toString();
	}

	/**
	 * disposition峴偺暘夝
	 */
	private String[] dispositionParse(String line) {
		filepart = false;
		String jisline=null;
		String[] ret = new String[2];
		String lowerline = line.toLowerCase();

		int start = lowerline.indexOf("content-disposition: ");
		int end = lowerline.indexOf(";");

		if( (start == -1)||(end == -1) ) return null;
		String disposition = lowerline.substring(start + 21, end);
		if( !disposition.equals("form-data")) return null;

		// 僼傿乕儖僪柤庢摼
		start = lowerline.indexOf("name=\"",end);
		end = lowerline.indexOf("\"",start + 7);
		if( (start == -1)||(end == -1) ) return null;
		String name = line.substring(start + 6, end);

		// 僼傽僀儖柤庢摼
		String filename = null;
		start = lowerline.indexOf("filename=\"", end + 2);
		end = lowerline.lastIndexOf('\"');
		if( (start != -1)&&(end != -1) ) {
			filepart=true;
			filename = line.substring(start + 10, end);
			// fullpath偐傜僼傽僀儖柤偩偗傪敳偒庢傞
			int filepath = Math.max(filename.lastIndexOf('/'),filename.lastIndexOf('\\'));
			if(filepath > -1) {
				filename = filename.substring(filepath + 1);
			}
		}

		try {
			ret[0] = new String(name.getBytes("ISO-8859-1"),"JISAutoDetect");
			if(filename==null) {
				ret[1]=null;
			} else {
				String agent = req.getHeader("User-Agent");
				if(agent==null) {
					ret[1] = new String(filename.getBytes("ISO-8859-1"),"JISAutoDetect");
				} else {
					agent = agent.toLowerCase();
					if(agent.indexOf("msie")!=-1||agent.indexOf("win")!=-1||agent.indexOf("mac")!=-1) {
						ret[1] = new String(filename.getBytes("ISO-8859-1"),"SJIS");
					} else {
						ret[1] = new String(filename.getBytes("ISO-8859-1"),"EUC-JP");
					}
				}
			}
		} catch(UnsupportedEncodingException e) {
			ret[1] = filename;
		}

		return ret;
	}

	/**
	 * Content-Type峴偺暘夝
	 */
	private String contentTypeParse(String line) throws IOException {

		String contentType = null;

		String lowerline = line.toLowerCase();

		if(lowerline.startsWith("content-type")) {
			int start = lowerline.indexOf(" ");
			if(start == -1)
				throw new IOException("僨乕僞僄儔乕:Content-Type");
			contentType = line.substring(start + 1);
		}

		return contentType;
	}


	private Object[] nextPart() throws IOException {

		// content-disposition 偺庢摼
		// content-disposition: form-data; name="hogehoge"丂傑偨偼
		// content-disposition: form-data; name="hogehoge"; filename="hogehoge" 
		String line = readLine();
		if(line == null)
			return null;
		else if(line.length() == 0)
			return null;
		String[] disposition = dispositionParse(line);
		if(disposition == null)
			throw new IOException("僨乕僞僄儔乕:Content-Disposition");
		String name = disposition[0];
		String filename = disposition[1];
		String contentType = null;

		// 嬻峴傑偨偼Content-Type
		line = readLine();
		if(line != null && line.length()>0 ) {
			// Content-Type 偺庢摼
			contentType =  contentTypeParse(line);
			if(contentType != null) {
				// 嬻峴傑偱撉傒崬傓
				while(true) {
					line = readLine();
					if( (line == null) )
						throw new IOException("僨乕僞僄儔乕");
					if(line.length()==0)
						break;
				}
			}
		}

		Object[] ret = null;

		// 僼傽僀儖僼傿乕儖僪
		if(filepart) {

			int result;
			byte[] lbytes = new byte[64*1024];
			boolean end=false,endCheck=true;
			byteArray.reset();

			do {
				endCheck=true;
				result = sis.readLine(lbytes,0,lbytes.length);
				if(result==-1) break;
				if( result >= boundary.length() ) {
					for(int i=0;i<boundary.length();i++) {
						if( boundary.charAt(i) != (char)lbytes[i] ) {
							endCheck=false;
							break;
						}
					}
					if(endCheck)
						end = true;
				}

				if((!end) && (result != -1))
					byteArray.write(lbytes,0,result);
			} while(!end);

			ret = new Object[4];
			ret[0] = name;
			ret[1] = filename;

			if(contentType == null) {
				ret[2] = "application/octet-stream";
			} else {
				ret[2] = new String(contentType);
			}

			byte[] bytebuf;
			if(byteArray.size()>2) {
				bytebuf = new byte[byteArray.size()-2];
				System.arraycopy(byteArray.toByteArray(),0,bytebuf,0,byteArray.size()-2);
				ret[3] = bytebuf;
			} else {
				ret[3] = null;
			}
		}
		// 暥帤楍僼傿乕儖僪
		else {
			StringBuffer sb = new StringBuffer();
			boolean end = true;
			do {
				StringBuffer sbuf = readLine2();
				if( sbuf==null ){
					return null;
				}
				String s = sbuf.toString();
				if( s.startsWith(boundary) ){
					end = false;
				}else{
					sb.append(sbuf.toString());
				}
			}while(end);
			sb.setLength(sb.length()-2); // \r\n傪嶍彍
			ret = new Object[2];
//  			ret[0] = name;
//  			ret[1] = sb.toString();
  			ret[0] = new String(name.getBytes("ISO-8859-1"),"JISAutoDetect");
  			ret[1] = new String(sb.toString().getBytes("ISO-8859-1"),"JISAutoDetect");

		}

		return ret;
	}

	public void parse() throws GSException {
		String line;

		// 僒僀僘僠僃僢僋
		if(maxSize > 0) {
			int length = req.getContentLength();
			if(length > maxSize)
				throw new GSException("僒僀僘僆乕僶乕");
		}

		try {
			sis = req.getInputStream();
		} catch(IOException e) {
			throw new GSException("ServletInputStream偺庢摼偵幐攕",e);
		}

		// 嵟弶偺 boundary 傪庢摼
		try {
			line = readLine();
		} catch(IOException e) {
			throw new GSException("ServletStream偐傜撉崬傒幐攕",e);
		}
		if(line == null)
			throw new GSException("僨乕僞僄儔乕");
	    if (!line.startsWith(boundary))
	    	throw new GSException("僨乕僞僄儔乕(嬻僨乕僞)");

		hash = new Hashtable();

		// 奺part偺庢摼
		while(true) {

			// 抣偺庢摼
			Object[] ret;
			try {
				ret = nextPart();
			} catch(IOException e) {
				throw new GSException("part僨乕僞庢摼僄儔乕",e);
			}

			if(ret==null)
				break;

			// 暥帤楍僼傿乕儖僪
			if(ret.length == 2) {
				String[] value = (String[])hash.get( (String)ret[0] );
				if(value==null) {
					String[] values = new String[1];
					values[0] = (String)ret[1];
					hash.put((String)ret[0],values);
				}else{
					String[] values = new String[value.length+1];
					for(int i=0;i<value.length;i++)
						values[i] = value[i];
					values[value.length]=(String)ret[1];
					hash.put((String)ret[0],values);
				}
			}
			// 僼傽僀儖僼傿乕儖僪
			else if(ret.length == 4) {
				Hashtable value = new Hashtable(3);
				value.put("filename",(String)ret[1]);
				value.put("content-type",(String)ret[2]);
				if(ret[3]!=null)
					value.put("content",(byte[])ret[3]);
				else
					value.put("content",new byte[0]);
				hash.put((String)ret[0],value);
			}
		}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?