File Upload With Servlets Example!

Go, go, go!

Directory Layout

Create a new Maven project:
mvn archetype:generate -DgroupId=biz.tugay.fileupload -DartifactId=file-upload -DarchetypeArtifactId=maven-archetype-webapp

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.fileupload</groupId>
    <artifactId>file-upload</artifactId>
    <packaging>war</packaging>
 
    <version>1.0-SNAPSHOT</version>
 
    <name>file-upload 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>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>file-upload</finalName>
    </build>
</project>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
</web-app>

index.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <title>File Upload With Servlets Example</title>
    <meta charset="utf-8">
</head>
<body>
<div style="margin-top: 50px">
    <form action="${pageContext.request.contextPath}/uploadFile"
          enctype="multipart/form-data" method="post">
            <input type="file" name="attachment"/>
            <button type="submit" class="btn">Submit</button>
    </form>
    <%--@elvariable id="uploadedFileNames" type="java.util.Set<java.lang.String>"--%>
    <c:forEach items="${requestScope.uploadedFileNames}" var="fileName">
        <p><img src="${pageContext.request.contextPath}/attachments/${fileName}"/></p>
    </c:forEach>
</div>
</body>
</html>

UploadFileServlet.java
package biz.tugay.fileUpload;
/* User: koray@tugay.biz Date: 24/06/15 Time: 09:21 */
 
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;
import java.util.HashSet;
import java.util.Set;
 
@WebServlet(urlPatterns = "/uploadFile")
@MultipartConfig()
public class UploadFileServlet extends HttpServlet {
 
    private static final String uploadDirectory = "/attachments/";
    Set<String> uploadedFileNames = new HashSet<String>();
 
    @Override
    public void init() throws ServletException {
        // Create upload directory if not exists on init:
        File file = new File(getServletContext().getRealPath(uploadDirectory));
        if (!file.exists())
            file.mkdir();
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html; charset=UTF-8");
        Part filePart = req.getPart("attachment");
        if (filePart != null && filePart.getSize() > 0) {
            InputStream inputStream = filePart.getInputStream();
            String destination = getServletContext().getRealPath(uploadDirectory);
            File attachedFile = new File(destination + filePart.getSubmittedFileName());
            FileOutputStream outputStream = new FileOutputStream(attachedFile);
            final byte[] bytes = new byte[1024];
            while (inputStream.read(bytes) != -1) {
                outputStream.write(bytes);
            }
            outputStream.flush();
 
            uploadedFileNames.add(filePart.getSubmittedFileName());
        }
        req.setAttribute("uploadedFileNames",uploadedFileNames);
        req.getRequestDispatcher("/index.jsp").forward(req,resp);
    }
}


In Action!