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

public class UploadFile {
    private final   int         BUFFERSIZE = 8192;
    private final   int         MAXTOKEN   = 1024;
    private int                 bytesToRead = 1000000;
    private String              targetDir = "c:\\temp\\";
    private Vector  allFiles =  new Vector(16);
    private int     upindex  =  -1;

    public boolean uploadFile (InputStream isFromWeb) throws Exception {
        DataInputStream disFromWeb = new DataInputStream(isFromWeb);

        String boundary = disFromWeb.readLine()+"--";
        StringTokenizer stt = new StringTokenizer(disFromWeb.readLine(), "\"=\n");
        stt.nextToken(); stt.nextToken(); stt.nextToken();
        if (! stt.hasMoreElements()) return false;
        String filename = (new File(stt.nextToken())).getName();

        while (!disFromWeb.readLine().equals("")) ;

        byte    bytesBuffer[]          = new byte[BUFFERSIZE+MAXTOKEN];
        boolean end                    = false;
        int     allBytesRead           = 0;
        int     thisRead               = 0;
        int     lastRead               = 0;
        int     toProcess              = 0;   // Always equals to MAXTOKEN
        FileOutputStream outFileStream = new FileOutputStream(targetDir+"/"+filename);

        do {
            for (int i=0; i < toProcess; i++)
                bytesBuffer[i] = bytesBuffer[thisRead+i];
            thisRead = toProcess;

            int result;
            do {
                result = disFromWeb.read(bytesBuffer, thisRead, BUFFERSIZE);
            } while ((result != -1)  && ((thisRead += result) < MAXTOKEN));

            if (thisRead > MAXTOKEN) {
                thisRead -= MAXTOKEN;
                toProcess = MAXTOKEN;
            }
            else {
                thisRead -= boundary.length() + 4 /* CR+LF at 2 last lines */;
                end = true;
            }

            outFileStream.write(bytesBuffer, 0, Math.min(thisRead, bytesToRead - allBytesRead));
            allBytesRead += thisRead;
        } while ((! end) && (allBytesRead < bytesToRead));

        while (disFromWeb.read(bytesBuffer, 0, BUFFERSIZE) != -1) ;
        disFromWeb.close();
        outFileStream.close();

        allFiles.addElement(filename);
        return true;
    }

    public int getBytesToRead() {
        return bytesToRead;
    }

    public void setBytesToRead(int bytesToRead) {
        this.bytesToRead = bytesToRead;
    }

    public String getTargetDir() {
        return targetDir;
    }

    public void setTargetDir(String targetDir) {
        this.targetDir = targetDir;
    }

    public boolean getNextUpload() {
        if (++upindex < allFiles.size())
            return true;
        upindex = -1;
        return false;
    }

    public String getUploadFileName() {
        return (String) allFiles.elementAt(upindex);
    }
}
