Upload a File Using JSP

SHARE & COMMENT :

In general file upload means to receive data from a remote system to a local system. So coming to programming language a JSP can upload file on server by using html form tag. An uploaded file could be text file, image file or any document file.

In JSP we can upload files using multipart/form –data. This can be used to when we need to upload files on server. If we upload large files of mime-types or content types then JSP doesn’t process the request. So we should set maximum file size of in the property files. To upload single file we use single tag with attribute type =”file”. If we want upload multiple files then we should use more than one tag with different values with name attribute.

Creating a File Upload Form

To upload a file on server we can make use of <form> tag. It can be written as follows:

<form action="UploadFile.jsp" method="post" enctype="multipart/form-data">

where:

  • action attribute: It is url of the script the content should be sent to, means it is used to forward request to another resource.
  • method attribute: it specifies HTTP method to be used when sending form data. It can be post or get. But here we are setting it to post method.
  • enctype attribute: It is used to upload files on server using method called “multipart/form-data”

Upload File Example

  1. First we will create one Jsp file called index.jsp. It contains <form> which is used to upload file and forward request to another resource and HTTP method type post.
  2. FileUploader Servlet and handles the request for file upload and uses Apache FileUpload library to parse multipart form data.
  3. Configure servlet and JSP details in web.xml
  4. Create second Jsp file called as result.jsp . It will display the message whether the file is uploaded successfully or not using requestScope["message"] method.
  5. To execute this program you would need to include in your WEB-INF/lib folder.
    • commons-fileupload-1.3.jar
    • commons-io-2.4.jar
    • javax.servlet-api-3.0.1.jar

Listing 1: FileUploadHandler

package javabeat.net.jsp.file;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadHandler extends HttpServlet{
	private final String UPLOAD_DIRECTORY = "/home/manisha/Desktop";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //process only if its multipart content
        if(ServletFileUpload.isMultipartContent(request)){
            try {
                List<FileItem> multiparts = new ServletFileUpload(
                      new DiskFileItemFactory()).parseRequest(request);

                for(FileItem item : multiparts){
                    if(!item.isFormField()){
                        String name = new File(item.getName()).getName();
                        System.out.println("name "+name);
                        item.write(
                          new File(UPLOAD_DIRECTORY + File.separator + name));
                    }
                }

               //File uploaded successfully
               request.setAttribute("message", "File Uploaded Successfully");
            } catch (Exception ex) {
               request.setAttribute("message", "File Upload Failed due to " + ex);
            }

        }else{
            request.setAttribute("message",
                   "Sorry this Servlet only handles file upload request");
        }

        request.getRequestDispatcher("/result.jsp").forward(request, response);

    }

}

Listing 2: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>HelloWorldJSP</display-name>
 <servlet>
        <servlet-name>FileUploadHandler</servlet-name>
        <servlet-class>javabeat.net.jsp.file.FileUploadHandler</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>FileUploadHandler</servlet-name>
        <url-pattern>/upload</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

  <context-param>
    <description>Location to store uploaded file</description>
    <param-name>file-upload</param-name>
    <param-value>
         /home/manisha
     </param-value>
</context-param>

</web-app>

Listing 3: hello.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<div>
    <h3> Choose File to Upload in Server </h3>
    <form action="upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" value="upload" />
    </form>
</div>

</body>
</html>

Listing 4: result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="result">
   <h3>${requestScope["message"]}</h3>
</div>
</body>
</html>

Execute the jsp file hello.jsp in Eclipse by selecting Run As > Run On Server.

Previous Tutorial : Auto Refresh using JSP || Next Tutorial : How to send mail in JSP

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better