package com.myUpload;

import java.io.*;
import java.util.*;

public class MyUpload {

	private HashMap arguments = new HashMap();
	
	public String getParameter(String name) {
		return (String)arguments.get(name);
	}
	
	public void upload(String boundary, InputStream in, String path)
				throws IOException
	{
		DataInputStream reader= new DataInputStream(in);
		String line;

		while((line=reader.readLine()) != null) {
			if(line.equals(boundary))
				return;
			
			line = reader.readLine();
			int index = line.indexOf("; filename=\"");	
			
			if(index == -1) {//²ÎÊý
				int i = line.indexOf("name=");
				String name = line.substring(i+6);
				name = name.substring(0, name.length()-1);
				
				reader.readLine();
				String value = reader.readLine();
				
				arguments.put(name, value);
			} else { //ÎÄ¼þ
				String filename = line.substring(index+12);
				int i = filename.lastIndexOf(File.separator);
				filename = filename.substring(i+1);
				filename = filename.substring(0, filename.length()-1);

				while((line=reader.readLine()) != null) {
					if(line.trim().length() == 0)
						break;
				}
				FileOutputStream out  = new FileOutputStream(path + filename);

				byte []buf = new byte[4096];
				int count = 0;
				int avail = 0;
				while(true) {
					count = in.read(buf, 0, 4096);
					if(count<0)
						break;

					out.write(buf, 0 ,count);
					out.flush();
				}
				out.close();
			}	
		}

	}
	
/*	
	public static void main(String []args) {
		try{
			FileInputStream in = new FileInputStream("D:\\a.txt");
			new MyUpload().upload("-----------------------------7d51c596e00ac", in, "D:\\");
		}catch(Exception e){
		}
	}
*/
}