Skip to content

File upload and download using Servlet ‚Äč

In this journey, we're going to unpack the magic of Servlets, those Java-based classes that handle web requests. We'll explore how to create a seamless experience for users to effortlessly upload their files to your web app. And guess what? We'll also learn how to let users retrieve those files whenever they need them.

java
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

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;

@WebServlet("/FileUploadServlet")
@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;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        
        // Get the file part from the request
        Part filePart = request.getPart("file");
        
        // Get the name of the file
        String fileName = filePart.getSubmittedFileName();
        
        // Specify the directory to save the uploaded file
        String savePath = "C:\\uploads" + File.separator + fileName;
        
        // Save the file to the specified directory
        filePart.write(savePath);
        
        // Display a message to the user
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h2>File " + fileName + " has been uploaded successfully!</h2>");
        out.println("</body></html>");
    }
}

In this code example:

  1. We import necessary classes for file handling and servlet functionalities.
  2. We define a servlet class named FileUploadServlet.
  3. We override the doPost method since we're handling file uploads via HTTP POST requests.
  4. We set up the servlet to handle multipart/form-data requests using @MultipartConfig annotation.
  5. Inside the doPost method, we retrieve the file part from the request using request.getPart("file").
  6. We extract the filename from the file part.
  7. We specify the directory where we want to save the uploaded file.
  8. We write the contents of the file part to the specified directory using filePart.write(savePath).
  9. Finally, we display a success message to the user confirming the successful upload.

Remember to adjust the savePath variable according to the directory where you want to save the uploaded files on your server.

java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/FileDownloadServlet")
public class FileDownloadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Get the file name from the request
        String fileName = request.getParameter("fileName");
        
        // Specify the directory where the file is located
        String filePath = "C:\\uploads" + File.separator + fileName;
        
        // Set the content type for the response
        response.setContentType("application/octet-stream");
        
        // Set the header for the response to suggest file name when downloading
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        
        // Read the file and write it to the response output stream
        try (FileInputStream fis = new FileInputStream(filePath);
             OutputStream os = response.getOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this code:

  1. We create a new servlet class named FileDownloadServlet.
  2. We override the doGet method since file downloads are typically initiated via GET requests.
  3. We retrieve the file name to be downloaded from the request parameters.
  4. We specify the path to the file to be downloaded.
  5. We set the content type of the response to application/octet-stream, which suggests to the browser that it should prompt the user to download the file.
  6. We set the Content-Disposition header to specify the filename for the downloaded file.
  7. We read the file from the specified path and write its contents to the response output stream.

Make sure to adjust the filePath variable according to the directory where your uploaded files are stored on the server.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.