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>