java file upload example with servlet 30 api

Here is an example of how to implement file upload in a Java web application using the Servlet 3.0 API:

  1. Create a form in an HTML or JSP page for the user to select a file to upload:
<form action="upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" value="Upload" />
</form>
Source‮ww:‬w.theitroad.com
  1. Create a servlet to handle the file upload:
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.servlet.ServletException;
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;

@WebServlet("/upload")
public class FileUploadServlet extends HttpServlet {
    private static final String UPLOAD_DIR = "uploads";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Get the file part from the request
        Part filePart = request.getPart("file");

        // Get the file name and content type
        String fileName = filePart.getSubmittedFileName();
        String contentType = filePart.getContentType();

        // Create the upload directory if it doesn't exist
        Path uploadDir = Paths.get(getServletContext().getRealPath("") + File.separator + UPLOAD_DIR);
        if (!Files.exists(uploadDir)) {
            Files.createDirectory(uploadDir);
        }

        // Save the file to the upload directory
        Path file = uploadDir.resolve(fileName);
        try (InputStream input = filePart.getInputStream()) {
            Files.copy(input, file);
        }

        response.sendRedirect("success.jsp");
    }
}
  1. Configure the servlet in the deployment descriptor (web.xml) or using annotations. Here is an example using annotations:
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = { "/upload" }, initParams = {
        @WebInitParam(name = "upload-dir", value = "/uploads") })
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
        maxFileSize = 1024 * 1024 * 10, // 10MB
        maxRequestSize = 1024 * 1024 * 50) // 50MB
public class FileUploadServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private static final String SAVE_DIR = "uploadFiles";

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String appPath = request.getServletContext().getRealPath("");
        String savePath = appPath + File.separator + SAVE_DIR;

        File fileSaveDir = new File(savePath);
        if (!fileSaveDir.exists()) {
            fileSaveDir.mkdir();
        }

        for (Part part : request.getParts()) {
            String fileName = extractFileName(part);
            part.write(savePath + File.separator + fileName);
        }

        request.setAttribute("message", "Upload has been done successfully!");
        getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
    }

    private String extractFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] items = contentDisp.split(";");
        for (String s : items) {
            if (s.trim().startsWith("filename")) {
                return s.substring(s.indexOf("=") +