Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

The code below allows you to select an image file from the local file system, upload it, and display it in the browser. Any review is welcome. You can see the code in action here.

Here is my code:

package biz.tugay.fileUpload;
/* User: [email protected] 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);
    }

}

and index.jsp is as follows:

<%@ 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><%@ 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>
share|improve this question
6  
To make life easier for reviewers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. See also this meta question –  Quill Jun 24 at 7:42
1  
"Example"?? Please keep in mind example code is off-topic on codereview. –  Vogel612 Jun 24 at 7:43
    
@Vogel612 What do you mean example code? –  Koray Tugay Jun 24 at 7:56
    
From the title of your JSP I understand that this is not the actual (as close as possible to) production code that you show here, correct? In other words this code is but an example of how your real code looks, right? –  Vogel612 Jun 24 at 7:58
2  
@Vogel612 What do you mean production code? I am just learning and doing some examples. –  Koray Tugay Jun 24 at 8:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.