来源水木清华
public class uploadservlet extends httpservlet
{
//default maximum allowable file size is 100k
static final int max_size = 102400;
//instance variables to store root and success message
string rootpath, successmessage;
/**
* init method is called when servlet is initialized.
*/
public void init(servletconfig config) throws servletexception
{
super.init(config);
//get path in which to save file
rootpath = config.getinitparameter("rootpath");
if (rootpath == null)
{
rootpath = "/";
}
/*get message to show when upload is complete. used only if
a success redirect page is not supplied.*/
successmessage = config.getinitparameter("successmessage");
if (successmessage == null)
{
successmessage = "file upload complete!";
}
}
/**
* dopost reads the uploaded data from the request and writes
* it to a file.
*/
public void dopost(httpservletrequest request,
httpservletresponse response)
{
servletoutputstream out=null;
datainputstream in=null;
fileoutputstream fileout=null;
try
{
/*set content type of response and get handle to output
stream in case we are unable to redirect client*/
response.setcontenttype("text/plain");
out = response.getoutputstream();
}
catch (ioexception e)
{
//print error message to standard out
system.out.println("error getting output stream.");
system.out.println("error description: " + e);
return;
}
try
{
//get content type of client request
string contenttype = request.getcontenttype();
//make sure content type is multipart/form-data
if(contenttype != null && contenttype.indexof(
"multipart/form-data") != -1)
{
//open input stream from client to capture upload file
in = new datainputstream(request.getinputstream());
//get length of content data
int formdatalength = request.getcontentlength();
//allocate a byte array to store content data
byte databytes[] = new byte[formdatalength];
//read file into byte array
int bytesread = 0;
int totalbytesread = 0;
int sizecheck = 0;
while (totalbytesread < formdatalength)
{
//check for maximum file size violation
sizecheck = totalbytesread + in.available();
if (sizecheck > max_size)
{
out.println("sorry, file is too large to upload.");
return;
}
bytesread = in.read(databytes, totalbytesread,
formdatalength);
totalbytesread += bytesread;
}
//create string from byte array for easy manipulation
string file = new string(databytes);
//since byte array is stored in string, release memory
databytes = null;
/*get boundary value (boundary is a unique string that
separates content data)*/
int lastindex = contenttype.lastindexof("=");
string boundary = contenttype.substring(lastindex+1,
contenttype.length());
//get directory web variable from request
string directory="";
if (file.indexof("name=\"directory\"") > 0)
{
directory = file.substring(
file.indexof("name=\"directory\""));
//remove carriage return
directory = directory.substring(
directory.indexof("\n")+1);
//remove carriage return
directory = directory.substring(
directory.indexof("\n")+1);
//get directory
directory = directory.substring(0,
directory.indexof("\n")-1);
/*make sure user didnt select a directory higher in
the directory tree*/
if (directory.indexof("..") > 0)
{
out.println("security error: you cant upload " +
"to a directory higher in the directory tree.");
return;
}
}
//get successpage web variable from request
string successpage="";
if (file.indexof("name=\"successpage\"") > 0)
{
successpage = file.substring(
file.indexof("name=\"successpage\""));
//remove carriage return
successpage = successpage.substring(
successpage.indexof("\n")+1);
//remove carriage return
successpage = successpage.substring(
successpage.indexof("\n")+1);
//get success page
successpage = successpage.substring(0,
successpage.indexof("\n")-1);
}
//get overwrite flag web variable from request
string overwrite;
if (file.indexof("name=\"overwrite\"") > 0)
{
overwrite = file.substring(
file.indexof("name=\"overwrite\""));
//remove carriage return
overwrite = overwrite.substring(
overwrite.indexof("\n")+1);
//remove carriage return
overwrite = overwrite.substring(
overwrite.indexof("\n")+1);
//get overwrite flag
overwrite = overwrite.substring(0,
overwrite.indexof("\n")-1);
}
else
{
overwrite = "false";
}
//get overwritepage web variable from request
string overwritepage="";
if (file.indexof("name=\"overwritepage\"") > 0)
{
overwritepage = file.substring(
file.indexof("name=\"overwritepage\""));
//remove carriage return
overwritepage = overwritepage.substring(
overwritepage.indexof("\n")+1);
//remove carriage return
overwritepage = overwritepage.substring(
overwritepage.indexof("\n")+1);
//get overwrite page
overwritepage = overwritepage.substring(0,
overwritepage.indexof("\n")-1);
}
//get filename of upload file
string savefile = file.substring(
file.indexof("filename=\"")+10);
savefile = savefile.substring(0,
savefile.indexof("\n"));
savefile = savefile.substring(
savefile.lastindexof("\\")+1,
savefile.indexof("\""));
/*remove boundary markers and other multipart/form-data
tags from beginning of upload file section*/
int pos; //position in upload file
//find position of upload file section of request
pos = file.indexof("filename=\"");
//find position of content-disposition line
pos = file.indexof("\n",pos)+1;
//find position of content-type line
pos = file.indexof("\n",pos)+1;
//find position of blank line
pos = file.indexof("\n",pos)+1;
/*find the location of the next boundary marker
(marking the end of the upload file data)*/
int boundarylocation = file.indexof(boundary,pos)-4;
//upload file lies between pos and boundarylocation
file = file.substring(pos,boundarylocation);
//build the full path of the upload file
string filename = new string(rootpath + directory +
savefile);
//create file object to check for existence of file
file checkfile = new file(filename);
if (checkfile.exists())
{
/*file exists, if overwrite flag is off, give
message and abort*/
if (!overwrite.tolowercase().equals("true"))
{
if (overwritepage.equals(""))
{
/*overwrite html page url not received, respond
with generic message*/
out.println("sorry, file already exists.");
}
else
{
//redirect client to overwrite html page
response.sendredirect(overwritepage);
}
return;
}
}
/*create file object to check for existence of
directory*/
file filedir = new file(rootpath + directory);
if (!filedir.exists())
{
//directory doesnt exist, create it
filedir.mkdirs();
}
//instantiate file output stream
fileout = new fileoutputstream(filename);
//write the string to the file as a byte array
fileout.write(file.getbytes(),0,file.length());
if (successpage.equals(""))
{
/*success html page url not received, respond with
generic success message*/
out.println(successmessage);
out.println("file written to: " + filename);
}
else
{
//redirect client to success html page
response.sendredirect(successpage);
}
}
else //request is not multipart/form-data
{
//send error message to client
out.println("request not multipart/form-data.");
}
}
catch(exception e)
{
try
{
//print error message to standard out
system.out.println("error in dopost: " + e);
//send error message to client
out.println("an unexpected error has occurred.");
out.println("error description: " + e);
}
catch (exception f) {}
}
finally
{
try
{
fileout.close(); //close file output stream
}
catch (exception f) {}
try
{
in.close(); //close input stream from client
}
catch (exception f) {}
try
{
out.close(); //close output stream to client
}
catch (exception f) {}
}
}
}
