Servlet File Upload

Uploading a file in a Java Servlet is a common requirement in web applications. The Servlet 3.0 API provides built-in support for file upload with the @MultipartConfig annotation and the Part interface. Here's a simple example:

1. HTML Form

First, you need an HTML form with enctype="multipart/form-data" and an <input type="file"> for the file:

<form action="upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" />
</form>

2. Servlet

Next, you need a Servlet to handle the file upload. Use the @MultipartConfig annotation to enable multipart/form-data requests, and use the getPart or getParts method to get the uploaded file(s):

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
        String fileName = filePart.getSubmittedFileName();
        InputStream fileContent = filePart.getInputStream();
        // ... (use fileContent)

        // You can also save the uploaded file to a specific location:
        File uploads = new File("/path/to/uploads");
        File file = new File(uploads, fileName);
        try (InputStream input = filePart.getInputStream()) {
            Files.copy(input, file.toPath());
        }
    }
}

In this example, getPart("file") gets the uploaded file, getSubmittedFileName() gets the original file name, and getInputStream() gets the file content.

If you want to save the uploaded file to a specific location, you can create a File object for the destination and use Files.copy to copy the file content to the destination.

Remember, always validate the uploaded file before using it. Check the file size, content type, and name to prevent malicious files from being uploaded, and handle exceptions properly.

Note: If you are using an older Servlet API or need more features (like progress tracking, limits, or advanced parsing), consider using a library like Apache Commons FileUpload.

  1. Java Servlet multipart request handling: Handle multipart requests for file uploads in a Servlet.

    @MultipartConfig
    public class FileUploadServlet extends HttpServlet {
        // Servlet code for handling file uploads
    }
    
  2. Servlet file upload example code: An example of handling file uploads in a Servlet.

    @MultipartConfig
    public class FileUploadServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            Part filePart = request.getPart("file");
            // Process the uploaded file
        }
    }
    
  3. Configuring file upload in Servlet: Configure the Servlet to handle file uploads by adding the @MultipartConfig annotation.

    @MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 2, // 2MB
        maxFileSize = 1024 * 1024 * 10,      // 10MB
        maxRequestSize = 1024 * 1024 * 50    // 50MB
    )
    
  4. Handling file upload limits in Servlet: Set limits on file size and request size in the @MultipartConfig annotation.

  5. Using FormData for file upload in Servlet: Use the FormData API for client-side file uploads.

    var formData = new FormData();
    formData.append('file', fileInput.files[0]);