Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Using oreilly's MultipartRequest to upload files and change file names...

843838Nov 23 2005
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
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 21 2005
Added on Nov 23 2005
0 comments
108 views