File Upload Example with Java Servlets + JSP


Here it is..

Directory Layout

pom.xml
<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>biz.tugay</groupId>
    <artifactId>updo</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
 
    <name>updo Maven Webapp</name>
    <url>http://maven.apache.org</url>
 
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>3.0.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
 
    <properties>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
 
    <build>
        <finalName>updo</finalName>
        <plugins>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.2.1.v20140609</version>
            </plugin>
        </plugins>
    </build>
 
</project>

web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
 
    <jsp-config>
        <jsp-property-group>
            <url-pattern>*.jsp</url-pattern>
            <page-encoding>UTF-8</page-encoding>
            <scripting-invalid>true</scripting-invalid>
            <trim-directive-whitespaces>true</trim-directive-whitespaces>
            <default-content-type>text/html;charset=UTF-8</default-content-type>
        </jsp-property-group>
    </jsp-config>
 
</web-app>

UpDoServlet.java
package biz.tugay;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
 
/**
 * User: Koray Tugay (koray@tugay.biz)
 * Date: 8/6/2016
 * Time: 6:06 PM
 */
 
@WebServlet(urlPatterns = "")
@MultipartConfig
public class UpDoServlet extends HttpServlet {
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        final String uploadsDirectory = getUploadsDirectory(req);
        final File uploadDir = new File(uploadsDirectory);
        final File[] files = uploadDir.listFiles();
        req.setAttribute("files", files);
        req.getRequestDispatcher("index.jsp").forward(req, resp);
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        final Part filePart = req.getPart("filePart");
        final String submittedFileName = filePart.getSubmittedFileName();
        final InputStream inputStream = filePart.getInputStream();
        final File file = new File(getUploadsDirectory(req) + submittedFileName);
        final FileOutputStream fileOutputStream = new FileOutputStream(file);
        int readByte;
        while ((readByte = inputStream.read()) != -1) {
            fileOutputStream.write(readByte);
        }
        inputStream.close();
        fileOutputStream.flush();
        fileOutputStream.close();
        resp.sendRedirect(getServletContext().getContextPath());
    }
 
    private String getUploadsDirectory(HttpServletRequest req) {
        return req.getServletContext().getRealPath("") +
                File.separator + "uploads" + File.separator;
    }
}

index.jsp
<%--
    User: Koray Tugay (koray@tugay.biz)
    Date: 8/6/2016
    Time: 6:04 PM
--%>
 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>UpDo</title>
</head>
<body>
<%--@elvariable id="files" type="java.io.File[]"--%>
<div>
    <form id="fileUploadForm" enctype="multipart/form-data" method="post">
        <label for="filePart">File:
            <input id="filePart" type="file" name="filePart"/>
        </label>
        <br/>
        <br/>
        <input id="fileUploadButton"
               type="submit"
               value="Submit file!">
    </form>
    <hr/>
    <c:forEach items="${files}" var="file">
        <img src="uploads/${file.name}" alt="${file.name}"/>
        <br />
    </c:forEach>
</div>
</body>
</html>

And in action: