Handling File Uploads in Web Applications Using the FormData Interface

Frontend Implementation

A typical HTML structure for file selection includes an <input type="file"> and an <img> element to preview the chosen image.

<input id="fileInput" type="file" accept="image/*" />
<img id="preview" alt="Preview" style="max-width: 400px; display: none;" />

The JavaScript logic reads the selected file, builds a FormData payload, and sends it to the server with the Fetch API.

const fileInput = document.getElementById('fileInput');
const previewImage = document.getElementById('preview');

fileInput.addEventListener('change', () => {
  const file = fileInput.files[0];
  if (!file) return;

  // Show a preview using FileReader
  const reader = new FileReader();
  reader.onload = (e) => {
    previewImage.src = e.target.result;
    previewImage.style.display = 'block';
  };
  reader.readAsDataURL(file);

  // Build FormData
  const form = new FormData();
  form.append('uploadFile', file);      // key used on the server

  // Send to a backend endpoint
  fetch('/upload', {
    method: 'POST',
    body: form
  })
    .then(response => {
      if (!response.ok) throw new Error('Upload failed');
      return response.json();
    })
    .then(data => {
      console.log('Server response:', data.message);
    })
    .catch(err => console.error('Network error:', err));
});

Backend Handling (Java Servlet)

On the server side, a servlet can process the uploaded file via the Part API, save it to a designated directory, and return a JSON acknowledgment.

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

  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    Part filePart = req.getPart("uploadFile");  // matches the key used in FormData
    String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();

    // Define an upload directory relative to the web application root
    String appPath = getServletContext().getRealPath("");
    File uploadDir = new File(appPath, "uploads");
    if (!uploadDir.exists()) {
      uploadDir.mkdirs();
    }

    // Save the file
    filePart.write(uploadDir.getAbsolutePath() + File.separator + fileName);

    // Respond with JSON
    resp.setContentType("application/json");
    resp.getWriter().write("{\"message\":\"File saved successfully\",\"file\":\""
        + fileName + "\"}");
  }
}

FormData API Quick Reference

  • append(name, value) – Adds a value to a key. If the key already exists, it creates an additional entry instead of overwriting. You can append multiple values under the same key.
  • delete(name) – Removes all entries associated with the given key. No error is thrown if the key does not exist.
  • get(name) – Returns the first value linked to the key, or null if the key is absent.
  • getAll(name) – Returns an array containing all values for the key. An empty array is returned when the key is not present.
  • has(name) – Checks whether a key exists in the FormData object.
  • set(name, value) – Replaces the value of a key. If the key has multiple entries, only the first is overwritten; subsequent entries are removed. If the key does not exist, its created.
  • entries() – Returns an iterator that yields [key, value] arrays for every entry.
  • forEach(callback) – Iterates over entries, calling the provided function with arguments (value, key, formData).
  • keys() – Returns an iterator of all key.
  • values() – Returns an iterator of all values.
  • Symbol.iterator – Allows direct iteration of a FormData instance using for...of, providing [key, value] pairs.

Tags: FormData javascript File Upload servlet HTML5

Posted on Sun, 07 Jun 2026 17:35:27 +0000 by nishanthc12