Core Java| JSP| Servlets| XML| EJB| JEE5| Web Services| J2ME| Glossary| Questions?

 

 

 

 

 

 

 

 

 

 

 

 

 

Search Tutorials

Latest Questions
Comments
 
Uploading Multiple Files Using Jsp 
 

This tutorial will help you to understand how you can upload multiple files by using the Jsp. We should avoid to use Jsp for performing any logic, as Jsp is mainly used for the presentation logic, but at least we should know how we can use a java code ins

 

Uploading Multiple Files Using Jsp

                         

This tutorial will help you to understand how you can upload multiple files by using the Jsp. We should avoid to use Jsp for performing any logic, as Jsp is mainly used for the presentation logic, but at least we should know how we can use a java code inside the jsp page. In Jsp the logic of the program is mainly written inside the scriptlet. In this example we are going to tell you how can make use of scriptlet to upload a file.

In this example we are going to tell you how we can upload multiple files by using Jsp and how they will get stored on the particular memory area. To get the desired result firstly we need to need to make a jsp page which will work as a controller and where we need to import some packages, classes and interfaces. For this program we need many classes and interfaces. 

The classes and interfaces we have used in the program are List and Iterator of java.util.* package, ServletFileLoad class of package org.apache.commons.fileupload.servlet.*, DiskFileItemFactory class of package org.apache.commons.fileupload.disk.DiskFileItemFactory and package org.apache.commons.fileupload.*. These are the classes which have been provided to us by the apache to help us in file uploading.

Inside the scriptlet call the isMultipartContent() method of class ServletFileUpload which takes one parameter request. This method checks whether there is a file upload request or not. It returns the boolean value. If there is a request for uploading the file then it makes a object of DiskFileItemFactory class and implements FileItemFactory. The implementation of FileItemFactory means that it creates FileItem instances which keep their content either in memory or disk. While using the DiskFileItemFactory the temporary files are automatically deleted as soon as they are no longer needed. The interface FileItemFactory is a factory for creating FileItem instances. 

Previously we have used one word FileItem, this interface represents a file or form item that was received within a multipart/form-data POST request.  Now pass the object of FileItemFactory which has the reference of class DiskFileItemFactory inside the constructor of class ServletFileUpload(). This is used to constructs an instance of this class which uses the supplied factory to create FileItem instances. Now declare a variable of type List with the initial value null. Use the method parseRequest() and pass a request object as its parameter which returns a list of FileItem instances parsed from the request, in the order they were transmitted. This method will throw FileUploadException if there is any problem while reading or parsing the request. Don't worry this is not going to happen in this example. 

To iterate the list of FileItem instances parsed from the request use a method iterator() of interface List which returns an iterator over the elements in this list in proper sequence. To get the list of FileItem instances we need to make use of while loop This loop will continue until the end of FileItem doesn't reached. 

After all this we need to save the file to the particular location. Create a object of File class of package java.io.* package. The constructor of the File class takes one parameter. The parameter we are passing in this constructor reflects the place where the file will get stored.

Now make another jsp page which will be used for the presentation. In this Jsp page we will have one action which tells where the request will be forwarded when there is any request for file uploading. The request will be sent in the form of post method, In post method the parameters are send within a message body. As we have to upload multiple files so we need enctype. This is used to determine how the data is encoded. Whenever data is transmitted from one place to another, there should be some agreement between the party how the data will be represented. 

In our example we are uploading three files at a time so we need three input of type "file" and one "submit" button with value "Submit Files". As soon as the user click on the submit button the request will be forwarded to the controller. 

Here is the code of the upload_file_multipale.html file:

<html>
 <head><title>Upload page</title></head></p> <p><body>
 <form action="upload_file_multipale.jsp" method="post" enctype="multipart/
form-data" name="form1" id="form1">
   <center>
   <table border="2">
       <tr>
	       <td align="center"><b>Multipale file Uploade</td>
	   </tr>
       <tr>
	       <td>
		       Specify file: <input name="file" type="file" id="file">
		   <td>
	   </tr>
	   <tr>
	      <td>
		     Specify file:<input name="file" type="file" id="file">
		  </td>
        <tr>
		   <td>
		      Specify file:<input name="file" type="file" id="file">
		   </td>
		 </tr>
		 <tr>
		    <td align="center">
               <input type="submit" name="Submit" value="Submit files"/>
			</td>
		 </tr>
    </table>
	<center>
 </form>
 </body>
 </html>

Output of the program is given below:

Here is the code of the upload_file_multipale.jsp file:

 <%@ page import="java.util.List" %>
   <%@ page import="java.util.Iterator" %>
   <%@ page import="java.io.File" %>
   <%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
   <%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
   <%@ page import="org.apache.commons.fileupload.*"%>
   <%@ page contentType="text/html;charset=UTF-8" language="java" %>
   <center><table border="2">
        <tr><td><h1>Your files  uploaded </h1></td></tr>
   <%
 boolean isMultipart = ServletFileUpload.isMultipartContent(request);
 if (!isMultipart) {
 } else {
	   FileItemFactory factory = new DiskFileItemFactory();
	   ServletFileUpload upload = new ServletFileUpload(factory);
	   List items = null;
	   try {
		   items = upload.parseRequest(request);
	   } catch (FileUploadException e) {
		   e.printStackTrace();
	   }
	   Iterator itr = items.iterator();
	   while (itr.hasNext()) {
	   FileItem item = (FileItem) itr.next();
	   if (item.isFormField()) {
	   } else {
		   try {
			   String itemName = item.getName();
			   File savedFile = new File(config.getServletContext
().getRealPath("/")+"uploadedFiles/"+itemName);
			   item.write(savedFile);  
					
			   out.println("<tr><td><b>Your file has been saved 
at the loaction:</b></td></tr><tr><td><b>"+config.getServletContext().getRealPath
("/")+"uploadedFiles"+"\\"+itemName+"</td></tr>");
		   } catch (Exception e) {
			   e.printStackTrace();
		   }
	   }
	   }
   }
   %>
    </table>
   </center>

Output of the above program is given below:

Download all files.

                         

» View all related tutorials
Related Tags: c com jsp file ide files upload types multiple help load output get type ip examples vi tutorial ria this

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

13 comments so far (
post your own) View All Comments Latest 10 Comments:

Tks, it's was very useful and easy to learn for me

Posted by Mauricio on Friday, 12.19.08 @ 13:21pm | #82977

I don't know why but its strange..I am getting error java.io.FileNotFoundException: C:\Documents and Settings\Administrator\My Documents\NetBeansProjects\Portal\build\web\uploadedFiles\C:\Documents and Settings\Administrator\Desktop\untitled.bmp (The filename, directory name, or volume label syntax is incorrect)



any help appreciated thanks

Posted by Gladiaotr07 on Friday, 12.12.08 @ 15:16pm | #82696

hi...

i've tried to run your code, but there is an error said 'unable to compile class for JSP'. I used eclipse in linux redhat 5. I also already import commons-fileupload.jar and commons-io.jar..but it still doesnt work. can you help me?

Posted by faiz on Wednesday, 12.3.08 @ 01:09am | #82304

Good tutorial, but it does not work using IE7

Posted by sufchenko on Thursday, 11.13.08 @ 07:30am | #81642

hi

i m prateek

i want to upload single file to multiple system

means distributed uploading please help me

Posted by PRATEEK on Thursday, 10.30.08 @ 18:12pm | #81418

hello ! rose thank you for your example program ! you know im now work excillent!u

Posted by mary victory on Wednesday, 09.17.08 @ 06:10am | #79981

Hi RoseIndia,

Thank you very much for your multiple file upload live example..

It works great.

Thankyou very much.

Posted by Lakshman on Friday, 09.12.08 @ 20:14pm | #78934

Please help me because method parseRequest() throw exception in this program.
org.apache.jasper.JasperException: Exception in JSP: /multifileupload.jsp:23

20: out.print("<br>upload="+upload);
21: List items = null;
22: try {
23: items = upload.parseRequest(request);
24: } catch (FileUploadException e) {
25: e.printStackTrace();
26: }
root cause
javax.servlet.ServletException: org/apache/commons/io/output/DeferredFileOutputStream
root cause
java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream
What problem is there?

Posted by Dusan Sulovec on Sunday, 08.10.08 @ 12:03pm | #72048

this jsp is not wrkin...its givin an error in da line 18th..
i.e.
items=upload.parseRequest(request);
plz help me with this.. im in a serious need
regards
apurvi

Posted by apurvi on Monday, 07.7.08 @ 13:48pm | #66116

This is really nice for newcomers....
Thansk roseindia...

Posted by Kedar on Saturday, 08.18.07 @ 12:05pm | #23639

Training Courses
Tell A Friend
Your Friend Name
Software Solutions
Least Viewed
Most Rated
Recently Viewed
Search Tutorials

 

 
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Flex Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.