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