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>
|