We help IT Professionals succeed at work.

How do I do file uploads in JSP?

richardsimnett
on
487 Views
Last Modified: 2013-11-24
Hello,
I have a form where a user is supposed to be able to upload a file of any size to my webserver. Once uploaded it should just store the file in a set path on the webserver, for processing by a bash script. How do I do accomplish this in JSP?

Here is my form:

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

<div align=center>
<table border=0 cellpadding=0 cellspacing=0 width=80% height=600px>
    <tr>
        <td valign=top>
            <h1>New Job</h1>
           
            <div align=center>
                <form action="manager.jsp?where=savejob" method=post enctype="multipart/form-data">
                <table border=0 cellpadding=0 cellspacing=0 80%>
                    <tr>
                        <td>Job Name:</td><td><input type=text size=25 maxlength=25 name=jobname></td>
                    </tr>
                    <tr>
                        <td>List:</td><td><input type=file size=25 name=list></td>
                    </tr>
                    <tr>
                        <td colspan=2 align=right><br><br><input type=submit value="Create Job"></td>
                    </tr>
                </table>
                </form>
            </div>
        </td>
    </tr>
</table>
</div>

My manager.jsp simply detects "where" it is and has this with no output when I test it.

 <c:when test="${where == 'savejob'}">
                    ${param.list}<br><br>
                    Job Saved.
 </c:when>


A good explanation, and examples are worth 500 points.

Thanks,
Rick
Comment
Watch Question

student
CERTIFIED EXPERT
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
rrz,
 Im actually getting errors when I try to test that... here is what Im getting...

org.apache.jasper.JasperException: Unable to compile class for JSP

Generated servlet error:
/home/rick/.netbeans/5.5.1/apache-tomcat-5.5.17_base/work/Catalina/localhost/pvw/org/apache/jsp/manager_jsp.java:8: package org.apache.commons.fileupload does not exist
import org.apache.commons.fileupload.*;
^


Generated servlet error:
/home/rick/.netbeans/5.5.1/apache-tomcat-5.5.17_base/work/Catalina/localhost/pvw/org/apache/jsp/manager_jsp.java:9: package org.apache.commons.fileupload.servlet does not exist
import org.apache.commons.fileupload.servlet.*;
^


Generated servlet error:
/home/rick/.netbeans/5.5.1/apache-tomcat-5.5.17_base/work/Catalina/localhost/pvw/org/apache/jsp/manager_jsp.java:10: package org.apache.commons.fileupload.disk does not exist
import org.apache.commons.fileupload.disk.*;
^


Generated servlet error:
/home/rick/.netbeans/5.5.1/apache-tomcat-5.5.17_base/work/Catalina/localhost/pvw/org/apache/jsp/manager_jsp.java:11: package org.apache.commons.fileupload.util does not exist
import org.apache.commons.fileupload.util.*;
^


I have already included the .jar file from the commons kit in the netbeans project... I dont know why it cant find the classes.... Any ideas?

Thanks,
Rick

Author

Commented:
rrz,
Actually I take that back I have the code working... sorta. It goes through the upload process, but a file never shows up in the fileUploads directory. How do I fix this? Here is what I get when I investigate that directory for the file:

rick@rick-desktop:~/pvw/web/fileUploads$ ls
rick@rick-desktop:~/pvw/web/fileUploads$

Thanks,
Rick

Author

Commented:
rrz,
Also, the output from the file is weird... here is what it kicks out

Form field jobname with value test2 detected.
File field MLIST.TXT with file name MLIST.TXT detected.
MLIST.TXT was uploaded to the fileUploads folder.

Shouldn't the very first MLIST.TXT be the field name? in this case list?


Thanks,
Rick
Siva Prasanna KumarPrincipal Solutions Architect
CERTIFIED EXPERT
Top Expert 2006

Commented:
The example given by RRZ use jakarta commons filr upload so you need to have these jars in you Web-Inf/lib folder.

you can find these jars at

http://commons.apache.org/fileupload/

Author

Commented:
shivaspk,
yeah I got that fixed, it was just a matter of a rebuild in netbeans. The issue now is that the upload appears to work, except no file is ever written to the fileUploads directory.

Thanks,
Rick
rrzstudent
CERTIFIED EXPERT

Commented:
>Shouldn't the very first MLIST.TXT be the field name? in this case list?  
There is no guarantee for order. It is up to browser.
Did you look in logs for any error message ?    
Did you put  commons-fileupload-1.2.jar  into  Tomcat's lib(for Tomcat 6, or common/lib for Tomcat 5) folder ?  
You could try it the following way.  
<%@ page import="java.util.*,
                 java.io.*,
                 org.apache.commons.fileupload.*,
                 org.apache.commons.fileupload.servlet.*,
                 org.apache.commons.fileupload.disk.*"%>
<%
   RequestContext reqContext = new ServletRequestContext(request);
   if(FileUploadBase.isMultipartContent(reqContext)){
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List list;
        try{
            list = upload.parseRequest(request);
           } catch(FileUploadException fue){throw new ServletException(fue);}  
        for(int i = 0; i < list.size(); i ++) {
              FileItem item = (FileItem)list.get(i);
              if(item.isFormField()){
                                     //do something with them
              }else{
                   if(!item.getName().equals("")){
                   String fileName = new File(item.getName()).getName();
                   File file = new File(application.getRealPath("/fileUploads/" + fileName));
                   item.write(file);
                   out.print(fileName + " was uploaded to the fileUploads folder.<br/>");
                   }
              }
        }
   }else out.print("Wrong request.");
%>

Author

Commented:
rrz,
actually I found the files, they were being stored in my .war file in netbeans... is it supposed to do that? How do I get it to just write it to the local disk instead of the .war?

Thanks,
Rick
rrzstudent
CERTIFIED EXPERT

Commented:
>How do I get it to just write it to the local disk instead of the .war?  
You can change the file path.  For example I am on windows and I can upload to C:\aaaa\test\   by using  
File file = new File("C:\\aaaa\\test\\" + fileName);  
If you are Linux, then  use something like
File file = new File("/usr/local/test/" + fileName);

Author

Commented:
rrz,
ahhhh. ok man thanks for all the help.

Rick

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.