Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Jsp File_upload Uploading Multiple Files Using Jsp

Related Tutorials


 
 

Share on Google+Share on Google+

Uploading Multiple Files Using Jsp

Advertisement
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.

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: February 25, 2008

Related Tutorials

Discuss: Uploading Multiple Files Using Jsp   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:11
Tarun Dutta
February 3, 2012
Problem solved of NoFileFound Exception

change this line to "File savedFile = new File(config.getServletContext().getRealPath("/")"uploadedFiles/"+itemName);" this one "File savedFile = new File(config.getServletContext().getRealPath("/")+"uploadedFiles/"+itemName.substring(itemName.lastIndexOf("\\")+1));"
samuya
April 7, 2012
Working

Great!!! and Thanks ... It's working ................ Fully tested. Editted it littlebit for insertion in databse.
vaishalisingh
April 8, 2012
code not working

This code is giving various error in its jsp page how to rectify them as the pacages are not available to it
jai
May 26, 2012
doubt

am getting some errors.shall i add any external jar files???
aneev
June 16, 2012
random

where to give the destination path? and in getRealPath should we give the destination path?
Max
July 11, 2012
having issues over VPN

I used this code and worked perfectly over the network or when the server(tomcat 6) is on the same network but this is not working when i need to upload files over vpn connection which basically connects to the server through the VPN
Karanyot
September 15, 2013
Error upload_file_multipale.jsp file

Error code line --> items = upload.parseRequest(request);
raju
October 23, 2013
i want uploaded file will be stored in some folder

i want uploaded file will be stored in some specific folder then i will write a source code for that purpose ........... after store the values in database then the file will be stored but not visiable to me import java.lang.*; import java.io.*; import java.sql.*; import javax.sql.*; import java.util.Date; import java.util.ResourceBundle; import javax.servlet.*; import java.lang.NumberFormatException.*; import javax.servlet.http.*; import java.lang.NullPointerException; public class PostProfile extends HttpServlet { Connection con=null; Statement stmt=null; PreparedStatement pstmt=null; public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException,NullPointerException { res.setContentType("text/html"); PrintWriter pw=res.getWriter(); try { Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.println("driver loaded......"); con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","raju"); System.out.println("connection established......"); String s1=req.getParameter("email"); String s2=req.getParameter("pass"); String s3=req.getParameter("cpass"); String s4=req.getParameter("cname"); String s5=req.getParameter("cloc"); String s6=req.getParameter("mn"); String s7=req.getParameter("exp"); String s8=req.getParameter("mon"); String s9=req.getParameter("kskills"); String s10=req.getParameter("resh"); String s11=req.getParameter("cind"); String s12=req.getParameter("farea"); String s13=req.getParameter("edet"); String s14=req.getParameter("pgrd"); String s15=req.getParameter("doc"); String s16=req.getParameter("c1"); String s17=req.getParameter("c2"); String s18=req.getParameter("c3"); String s19=req.getParameter("ares"); pstmt=con.prepareStatement("insert into PostProfile values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); pstmt.setString(1,s1); pstmt.setString(2,s2); pstmt.setString(3,s3); pstmt.setString(4,s4); pstmt.setString(5,s5); pstmt.setString(6,s6); pstmt.setString(7,s7); pstmt.setString(8,s8); pstmt.setString(9,s9); pstmt.setString(10,s10); pstmt.setString(11,s11); pstmt.setString(12,s12); pstmt.setString(13,s13); pstmt.setString(14,s14); pstmt.setString(15,s15); pstmt.setString(16,s16); pstmt.setString(17,s17); pstmt.setString(18,s18); pstmt.setString(19,s19); pstmt.executeUpdate(); pw.println("<html><body><h2>"); pw.println(""); pw.println("</h2></body></html>"); } catch (NumberFormatException nx) { pw.println(nx); } catch(Exception e) { pw.println(e); } } }
shubham
April 21, 2014
HTTP Status 404 error

HTTP Status 404 - /upload/upload_file_multipale -------------------------------------------------------------------------------- type Status report message /upload/upload_file_multipale description The requested resource (/upload/upload_file_multipale) is not available. someone plz help and thanks!
DMCA.com