Sunday, November 25, 2012

File Uploading in Servlet

File Uploading :


As most of us have already done this file uploading operation As End User but so far we are not familiar with the internal moves of it. The moment we come to servlet level programming of file uploading we get to know How this concept works actually...

File Uploading is nothing but transferring a file from client System to Server System for persistence.

To work with File Uploading Concept of servlet, Servlet API is not capable enough to provide support for it.
There is no such predefine classes and interface to work with.
So In that case we have to take the support of Third Party API like javazoom api.Although there are multiple Third party vendors provide adequate support for file uploading in servlet.

Basically we require following 3 jar file(from javazoom api) to work with file uploading concept of servlet.

1)uploadbean.jar        (Main jar file)
2)cos.jar                    (Dependent jar file)
3)struts.jar                  (Dependent jar file)

Main jar file(uploadbean.jar) should be added to classpath and main & dependent(all 3) jar file should be added to WEB-INF/lib folder of our web application..

Upto here we done with Background preparation now the time is to see the coding part of it.

For a moment if we assume that we are uploading file somewhere At very first glance the picture comes in our mind is.....some html page and textboxeses along with browse button.....

It is very simple to create this html page ...

upload1.html

<html>
       <head>
             <title>Shows How to upload files</title>
       </head>
       <body>
              <form action="test1" method="post" name="upload" enctype="multipart/form-data">
                     Select File 1:<input type="file" name="uploadfile1"><br><br>
                     Select File 2:<input type="file" name="uploadfile2"><br><br>
                                        <input type="submit" value="Upload">
              </form>
      </body>
</html>


method="post"  :

---------------------
Get method does not support file uploading operation so it is mandatory to go with post method here

The following are diffrenet enctype attribute:

a)application/x-www-form-urlencoded
b)multipart/form-data
c)text/plain

if enctype="application/x-www-form-urlencoded"

------------------------------------------------------------------
Then http protocol translates/converts white spaces into "+" symbol and special charecter into hexadecimal value while transferring data/file from client machine to server machine.


if enctype="multipart/form-data"

------------------------------------------------
Here http protocol doesn't apply any conversion it transfers data/file as it is to server..
no changes at all....This is recommended enctype attribute value...

if enctype="text/plain"

-------------------------------------
here http protocol translates/converts white spaces into "+" symbol and does not translate special charecter while transferring data/file to server.


Now we are going to code servlet for this ...

UploadServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javazoom.upload.*;

public class UploadServlet extends HttpServlet
{
           public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
               {
                   try{
                         UploadBean ub=new UploadBean();
                         ub.setFolderstore("c:/store");
                         MultipartFormDataRequest mreq=new MultipartFormDataRequest(req);
                         ub.store(mreq);
                         PrintWriter pw=res.getWriter();
                         pw.println("<h1>File Successfully uploaded </h1>");

                         pw.close();
                       }
                          catch(Exception e)
                         {
                                e.printStackTrace();
                          }
            }
}


Line by line understanding of the Above Code
---------------------------------------------------------

UploadBean ub=new UploadBean();


Creating UploadBean class object, it is used for storing the uploaded file in a server storage area.

ub.setFolderstore("c:/store");


Here we are specifying the location where the uploaded file will go..

MultipartFormDataRequest mreq=new MultipartFormDataRequest(req);


To read the file which are uploaded along with the request, we need to convert ServletRequest obj into MultipartFormDataRequest obj...

ub.store(mreq);


To store the uploaded files into a server we need to call store(-) of UploadBean class by passing MultipartFornDataRequest obj as parameter.

In MultipartFormDataRequest there is method getFiles() and it is internally called by store() for reading the uploaded files.

web.xml

<web-app>
            <servlet>
                     <servlet-name>abc</servlet-name>
                     <servlet-class>UploadServlet</servlet-class>
            </servlet>
           <servlet-mapping>
                     <servlet-name>abc</servlet-name>
                     <url-pattern>/test1</url-pattern>
          </servlet-mapping>
</web-app>


Deploymenet directory Structure:


UploadApp
    |------------------WEB-INF
    |                              |---------classes
    |                                              |-------------UploadServlet.java
    |                                              |--------------UploadServlet.class
    |                              |------------web.xml
    |                              |------------lib
    |                                              |-----------uploadbean.jar
    |                                              |-----------cos.jar
    |                                              |-----------struts.jar
    |-----------upload.html



Deploye the following web application in tomcat server and test it with this url

    http://localhost:8080/UploadApp/upload.html

 

You will get this page first





Once we select the file by clicking on the button. and when we click on "Upload"

we'll get this page showing output.





 Now we can check whether this file has successfully Uploaded or not by going to the specify place.
In This example we have taken E:/strore folder....

That's all about Uploading a file in server through Servlet......







  

No comments:

Post a Comment