It took me some time to find out how to do this. I came across an archived forum posting from 2003 which helped me a bit. Here is the code that I use to upload files using my JSP (or you can use this with servlets) with the oreilly servlet library (you can find this at: http://www.servlets.com/cos/ - add it to your classpath or under /WEB-INF/lib/ of your webapplication)
import com.oreilly.servlet.MultipartRequest;
<snip>
MultipartRequest mpr = new
// this saves the file using the web application root directory, restricting to 5 MB
MultipartRequest(request,getServletContext().getRealPath("/")+"projectFiles/",5 * 1024 * 1024);
String fileName="";
Enumeration enumer = mpr.getFileNames();
while(enumer.hasMoreElements()){
try{
String name = (String)enumer.nextElement();
File uploadedFile= mpr.getFile(name);
fileName = uploadedFile.getName();
java.util.Date timeStamp = new Date();
String modifiedName = "id"+id+"file"+timeStamp.getHours()+timeStamp.getMinutes()+timeStamp.getSeconds()+"_"+fileName;
File renamedFile = new File(getServletContext().getRealPath("/")+"projectFiles/" + modifiedName);
fileName=renamedFile.getName();
boolean checkModified = uploadedFile.renameTo(renamedFile); // returns boolean
}catch(NullPointerException npe){
// nothing
}catch(Exception e){
// my email function, for the beginning I wanted to get errors that are produced. You can leave this out.
com.sun.gscc.backend.Email.sendMail("myemail@myself", "Fileupload error", "Exception for ID "+id+" and name "+fileName+": "+e.toString(), "noreply");
}
}
dailysun