Simple file upload tutorial using Apache Commons fileupload with build by Maven


This post is for beginners who want to use Apache commons fileupload to upload files. Maven is used for build and dependency management.

Note: I have specified the context root of the web application as cfp

We start with the index.jsp that provides the UI to upload the file.

<html>
    <body>
        <form name="fileform" action="/cfp/upload" method="POST" enctype="multipart/form-data">
            <input type="file" name="resume" value="" width="50" />
            <input type="submit" value="OK" />
       </form>
    </body>
</html>

The servlet that uses Commons fileupload and stores the files is as below.

 package com.thea.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author karthikeyanc
 */
public class FileUploadServlet extends HttpServlet {
    private static final int BYTE_READ_SIZE = 200000;
    private static final String STORAGE_LOCATION = "E:\\d4444\\filestore\\";
    private static final String TEMP_REPOSITORY = "E:\\d4444\\aas";

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, FileUploadException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            //Any file that is more than 5KB is stored in temporary repository. Feel free to change this value.
            factory.setSizeThreshold(5000);
            factory.setRepository(new File(TEMP_REPOSITORY));

            ServletFileUpload upload = new ServletFileUpload(factory);

            List<FileItem> items = upload.parseRequest(request);
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    InputStream is = item.getInputStream();
                    FileOutputStream os = new FileOutputStream(new File(STORAGE_LOCATION + item.getName() ));
                    byte[] b = new byte[BYTE_READ_SIZE];
                    int bytesRead = 0;
                    while ((bytesRead = is.read(b)) != -1) {
                        os.write(b, 0, bytesRead);
                    }

                    os.flush();
                    os.close();
                    is.close();

                }

            }

            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet FileUploadServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>File Uploaded</h1>");
            out.println("</body>");
            out.println("</html>");

        } finally {
            out.close();
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(FileUploadServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Now the web.xml of the web application

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

  <display-name>FileUpload Web Application</display-name>
    <servlet>
        <servlet-name>FileUploadServlet</servlet-name>
        <servlet-class>com.thea.servlet.FileUploadServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>FileUploadServlet</servlet-name>
        <url-pattern>/upload</url-pattern>
    </servlet-mapping>
    </web-app>

And finally the pom.xml used by Maven to build the war file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.thea</groupId>
    <artifactId>fileupload</artifactId>
    <packaging>war</packaging>
    <version>0.1</version>
    <name>fileupload Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>

            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>servlet-api</artifactId>
            <version>6.0.16</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>el-api</artifactId>
            <version>6.0.16</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>jsp-api</artifactId>
            <version>6.0.16</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>fileupload</finalName>
        <plugins>
           
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.0.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <properties>
        <netbeans.hint.deploy.server>Tomcat60</netbeans.hint.deploy.server>
    </properties>
</project>


 
 
 
 
Comments:

Post a Comment:
  • HTML Syntax: Allowed
 

« January 2009
SunMonTueWedThuFriSat
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
       
Today

Valid XHTML or CSS?

[This is a Roller site]
 
© Karthik