File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Servlets and the fly likes file upload sos Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "file upload sos" Watch "file upload sos" New topic
Author

file upload sos

amit malhotra
Ranch Hand

Joined: Aug 06, 2001
Posts: 30
friends i am stuck up at a particular place,please tell me as to how should i proceed in this case..
i am writing a code for file upload and the code is as it is given in a serlverts book by dustin callaway, the code is not working at my end....could some one please tell me a way out
i am on tomcat 3.2.1
here are the file, an html page and a servlet, the servlet has been compilied
html form
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>File Upload Example</title>
</head>
<body style="font-family: Verdana; font-size: 10pt" background="file:///D:/jakarta-tomcat-3.2.1/jakarta-tomcat-3.2.1/webapps/fileupload/BACKGROUND1.jpg">

<h4 align="center"><font color="#000080"><u>File Upload Servlet</u></font></h4>
<table border="0" width="84%" cellspacing="0" cellpadding="0">
<tr>
<td width="51%">

<form enctype="multipart/form-data" action="UploadServlet" method="post">
<p><font color="#000080">Press the <b> browse</b> button to select the file to upload and then click on the <b>Upload Button</b>
</font>
<p>
<font color="#000080">
 

<input type="hidden" name="directory" value="temp/" >
<input type="hidden" name="successPage" value="success.html">
<input type="hidden" name="OverWrite" value="false">
<input type="hidden" name=OverWritePage" value="overwrite.html">
</font></td>
<td width="50%">
<p align="center"><font color="#000080">
<br>
<input type="file" name="filename" value="" maxlength="255" size="50">
<br>
<br>
<input type="submit" value="Upload">
</font></p>
</td>
</tr>
</table>
</form>
</body>
</html>
servlet code
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class UploadServlet extends HttpServlet
{
static final int MAX_SIZE =102400;
String rootPath,successMessage;

public void init(ServletConfig config) throws ServletException
{
super.init(config);
rootPath = config.getInitParameter("RootPath");
if (rootPath == null)
{
rootPath="/";
}
successMessage = config.getInitParameter("SuccessMessage");
if (successMessage == null)
{
successMessage = "File Upload Complete ";

}
} // end of init() method


public void doPost(HttpServletRequest request,HttpServletResponse response)
{
ServletOutputStream out = null;
DataInputStream in = null;
FileOutputStream fileOut = null;

try
{
response.setContentType("text/plain");
out=response.getOutputStream();
} catch(IOException e)
{
System.out.println("Error getting the output stream");
System.out.println("Error description:"+e);
}
try
{
String contentType = request.getContentType();
if (contentType != null && contentType.indexOf("multipart/form-data") != -1)
{
in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
if (formDataLength > MAX_SIZE)
{
out.println("Sorry the file is too large to uploaad ");
out.flush();
return;
} // end of if

byte dataBytes[] = new byte[formDataLength];
int bytesRead=0;
int totalBytesRead=0;
while (totalBytesRead < formDataLength)
{
bytesRead = in.read(dataBytes,totalBytesRead,formDataLength);
totalBytesRead += bytesRead;
} // end of while

String file = new String(dataBytes);
dataBytes = null;
int lastIndex = contentType.lastIndexOf("=");
String boundary =contentType.substring(lastIndex+1,contentType.length());
String directory="";
if(file.indexOf("name =\"Directory\"") > 0);
{
directory = file.substring(file.indexOf("name=\"Directory\""));
directory=directory.substring(directory.indexOf("\n")+1);
directory = directory.substring(0,directory.indexOf("\n")-1);
if (directory.indexOf("..")>0)
{
out.println("Security Error: You cannot do this ");
return;
}
}// end of if
String successPage="";
if(file.indexOf("name=\"SuccessPage\"")>0)
{
successPage=file.substring(file.indexOf("name=\"SuccessPage\""));
successPage=successPage.substring(successPage.indexOf("\n")+1);
successPage=successPage.substring(successPage.indexOf("\n")+1);
successPage = successPage.substring(0,successPage.indexOf("\n")-1);
}
String overWrite;
if(file.indexOf("name=\"OverWrite\"")>0)
{
overWrite = file.substring(file.indexOf("name=\"OverWrite\""));overWrite = overWrite.substring(overWrite.indexOf("\n")+1);
overWrite = overWrite.substring(overWrite.indexOf("\n")+1);
overWrite = overWrite.substring(0,overWrite.indexOf("\n")-1);
}else // end of if
{
overWrite="false";
}// end of else
String overWritePage="";
if (file.indexOf("name=\"OverwritePage\"")>0)
{
overWritePage=file.substring(file.indexOf("name=\"OverWritePage\""));
overWritePage = overWritePage.substring(overWritePage.indexOf("\n")+1);
overWritePage = overWritePage.substring(overWritePage.indexOf("\n")+1);
overWritePage = overWritePage.substring(0,overWritePage.indexOf("\n")-1);
}
String saveFile = file.substring(file.indexOf("filename=\"")+10);
saveFile=saveFile.substring(0,saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+1,saveFile.indexOf("\""));
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n",pos)+1;
pos=file.indexOf("\n",pos)+1;
int boundaryLocation = file.indexOf(boundary,pos)-4;
String fileName = new String(rootPath+directory+saveFile);
File checkFile = new File(fileName);
if (checkFile.exists())
{
if (!overWrite.toLowerCase().equals("true"))
{
if (overWritePage.equals(""))
{
out.println("Sorry the file already exists");
}else // end of if
{
response.sendRedirect(overWritePage);
} // end of else
return ;
}// end of if
} // end of if

File fileDir = new File(rootPath+directory);
if (!fileDir.exists())
{
fileDir.mkdirs();
} // end of if
fileOut = new FileOutputStream(fileName);
fileOut.write(file.getBytes(),0,file.length());

if (successPage.equals(""))
{
out.println(successMessage);
out.println("File Written to "+fileName);
}else // end of if
{
response.sendRedirect(successPage);
}
}else
{
out.println("Request not multipart/form data");
}
} catch(Exception e)
{
try
{
System.out.println("Error in do Post:"+e);
out.println("An unexpected error has occoured");
out.println("Error description :"+e);
}catch(Exception ex)
{
}
finally
{
try
{
in.close();

}catch(Exception ex)
{
}
try
{
out.close();

}catch(Exception ex)
{
}
}
}
any sugessions will be of gr8 help
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

Just so you know, there is no way that most people will look through all that code, and for two reasons:

You don't provide the line number where you get a stack trace exception. If no exception is thrown, then please give someone an idea as to where *you* think the problem is. You must have a first idea?

Second, there is a very popular file upload package put out by www.servlets.com/cos aka: "com.oreilly.servlet". Many people use this package and have no problems. You can even view the source of the packages. If you don't want to use this package, you can look at his source code and see where the the code you want to use is maybe having trouble.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: file upload sos