Handling file upload With JSP

On web application, sometimes we need an interface that user can use to upload file to a server. Uploading file is an activity to add or copying file to a computer system with move a file that located on a local computer to a remote computer. We often meet the uploading file system on a web application. For example, web-mail application, web-mail application use file upload system as a feature for user who wants send an email with the attachment.

On java web application, uploading file has its own process, because, the concept of uploading file is different and little bit complicated. Even though there’s a lot java library that can make us creating File upload system easily, but there’s still plenty of developer who make their own File Upload system mechanism.

And now we will try to handle File Upload system on java. in order to make this File Upload system easier to understand, we will try it on jsp’s. We will also use the java library in this project. The libraries are common-file-upload released by Apache Foundation on their jakarta-common project. Please download this common-file-upload library here. And we also need another library, which is common-io library, this library is also from jakarta-common-project, please download the library here.

Now we go straight to the scenario of this file upload system:

  1. User open a form on our web application, and there’s a field that user have to fill to upload a file.

  2. The upload file will be handled by a process, and the file that uploaded by user will be located in a folder on our web application, the name of the folder is /file_uploaded.

  3. This /file_uploaded folder located on {app-serv}/webapps/{appl-context}/ where the {app-serv} is an installation folder of your application server (Tomcat, Jboss, Glassfish, etc) and {app-context} is our web application installation folder

For your next future development, please try to located the file that user uploaded not into a folder that located in app-context, but please located outside your {app-serv}.

Base on above scenario, that’s mean we will need a form with a standard html form with the enc-type is multipart/form-data. Why should be multipart/form-data? Because only this type of form can carry the data not only characters, but also can carry the data as a file. At the process, actually, the form will change the uploaded file into a byte-stream that will be carried through TCP/IP ports.

Unfortunately this blog didn’t allow us to write some html code, so please just download the source of the project here. After you’ve download, let’s discuss this form_upload.html file. As you can see, that on a line <form action=”process_upload.jsp” method=”post” enctype=”multipart/form-data”> there’s a sentence enctype=”multipart/form-data”, this is the things that makes a different between this file and others standard html form, this kind of form which can carry the file onto a remote/server computer.

On that line too, we can see the process of file will go thru and handled by process_upload.jsp. This process_upload.jsp file have a duty to receive a file sent by file_upload.html and then process the uploaded file by put it onto destination folder.

Now, let’s see the code on process_upload.jsp file:

<%@ page import="org.apache.commons.fileupload.DiskFileUpload" %>
<%@ page import="org.apache.commons.fileupload.FileItem" %>
<%@ page import="org.apache.commons.fileupload.FileUpload" %>
<%@ page import="java.io.File" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.List" %>
<%
    String test="";
    File savedFile = null;
    boolean isMultipart = FileUpload.isMultipartContent(request);
    if (!isMultipart) {
        System.out.println(" Form Is not Multipart...!!!");
        return;
    }
    DiskFileUpload upload = new DiskFileUpload();
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            System.out.println("Exception = " + e.getMessage());
        }

        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
               if (item.isFormField()){
                 test = request.getParameter("test");
              }else{
                File fullFile = new File(item.getName());
                System.out.println("Full File : " + fullFile);

                String sPath = getServletConfig().getServletContext().getRealPath("/file_uploaded");
                System.out.println("Path of saved =" + sPath);

                File savedFile = new File(sPath, fullFile.getName());

                try {
                    item.write(savedFile);
                } catch (Exception e) {
                    System.out.println("Error Happen when saving the file :" + e.getMessage());
                }
            }
......

Lets’ discuss above code :

<%@ page import="org.apache.commons.fileupload.DiskFileUpload" %>
<%@ page import="org.apache.commons.fileupload.FileItem" %>
<%@ page import="org.apache.commons.fileupload.FileUpload" %>
<%@ page import="java.io.File" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.List" %>

These lines is lines about how jsp can import the classes the might be needed later. Also in these lines, we can see the library of common-file-upload belongs to apache imported, there’s also another lines to import another java which is: java.io.File, java.util.Iterator, dan java.util.List.

And the next lines is

     String test="";
     File savedFile = null;
     boolean isMultipart = FileUpload.isMultipartContent(request);
    if (!isMultipart) {
        System.out.println(" Form Bukan Multipart...!!!");
        return;
    }

In these lines, we can see that there’s a variable named test which is String type, savedFile which is File type, and isMutipart as a boolean type, those variable directly initialized, to check whether the sender form is multipart/form-data type or not. If the sender form is not multipart type, then the process just ended by adding code return; on a lines, after print out information that the sender form is not multipart type.

If the form is multipart type so the process will continue with these lines below:

       DiskFileUpload upload = new DiskFileUpload();
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            System.out.println("Exception = " + e.getMessage());
        }

On these lines, there’s a new instantiated object mentioned as a variable which is named as upload. And there’s another variable declaration, named items with List type, but this variable filled with the null value. And then, there’s a try-catch block, with the statement try to parse the request that sent by the sender form and then the result of the parse filled in items variable that declared before. If process failed when parsing the request from the sender form, the code will pint out the Exception.

And then the next lines is:

    Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
        if (item.isFormField()){
                 test = request.getParameter("test");
              }else{
                File fullFile = new File(item.getName());
                System.out.println("File Lengkap : " + fullFile);

                String sPath = getServletConfig().getServletContext().getRealPath("/file_uploaded");
                System.out.println("Lokasi penyimpanan file =" + sPath);

           savedFile = new File(sPath, fullFile.getName());

                try {
                    item.write(savedFile);
                } catch (Exception e) {
                    System.out.println("Ada Kesalahan ketika menyimpan File :" + e.getMessage());
                }
            }
        }

Ok, this part is little bit difficult to explain, but let’s try to explain it. On the first line, there’s a initialize of Iterator object named as itr variable, which is the value directly filled by iterating items variable which had FileItem as a type and processed. And then this item variable checked, if item is field form so the test variable that declared above, filled by the value which is taken from sender form which is not a file.

And the opposite of above process, if item is not a field form, and we can assume directly that the item is a file that needs to upload. So, let’s take the file by creating new object with File type and named the variable as fullFile, and then fill the value of this variable by taking the item name. Next we’ll try to print-out to find out what file sent by form.

And then we create new variable here called sPath with String the string as a type, this variable is made in order to define the location of the uploaded file will be saved.

In these lines we can see that the uploaded file will be saved on a folder called file_uploaded which is located on our web app installation. After we define the location of the saved file, now we do the processing of save file.

The next lines, there’s an object variable with File type called savedFile that we declared before, the value of this object variable filled by creating new File object that arrange based on file location(sPath) and the name of file fullFile.getName().

After this object is created, then we try to write new file by calling write methods that owned by item variable which FileItem type. And don’t forget to put the code on try-catch block to catch the error that could be happen if the file cannot be saved on the destination folder.

To try out the source that maybe you have download, just copy the whole source of the project to your {app-serv}/webapps/. Where {app-serv} is a folder where your Application Server or Your Servlet Container such as Tomcat installed. No need to compile here, cos the source only contains jsp’s and the library that needed. These source files is put and arranged in the correct location, so you just need to copy into your webapps folder and the restart your Application Server/Servlet Container.

Thnks

I Hope this Will Helpfull

Josescalia

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s