Go to content
Web development

Uploading Files with Fetch and FormData

When a user selects a file in a browser, your JavaScript code can send it in a FormData object with Fetch. FormData packages form fields and files in the multipart format, a request format that separates each field and file. Upload endpoints commonly read this format. Leave Content-Type unset in the Fetch options. The browser adds the header and a matching boundary, which marks where each field in the request body begins and ends.

Check uploaded files on the server before handling them.

Append the file and related fields

Give the file input a name, then get the selected file from its files list. Use FormData.append() to add the file and any related values under the field names your server expects:

<form id="upload-form">
  <label>
    File
    <input type="file" name="file" required>
  </label>

  <label>
    Description
    <input type="text" name="description">
  </label>

  <button type="submit">Upload</button>
</form>
const form = document.querySelector("#upload-form");

form.addEventListener("submit", async (event) => {
  event.preventDefault();

  const fileInput = form.elements.file;
  const file = fileInput.files[0];

  if (!file) {
    return;
  }

  const data = new FormData();
  data.append("file", file);
  data.append("description", form.elements.description.value);

  const response = await fetch("/uploads", {
    method: "POST",
    body: data,
  });

  if (!response.ok) {
    throw new Error(`Upload failed: ${response.status}`);
  }
});

The first argument to append() is the field name the server receives, and the second is the value for that field. A file selected in the browser is a File, a kind of Blob (data stored as a group of bytes) that also includes a filename. The FormData append documentation explains how to add a selected file under a field name. If you append a number or another non-string value, FormData converts it to a string. Convert values yourself when the server expects a specific format.

If the page already has a form, new FormData(form) collects values from its named controls. You can then append extra fields before calling Fetch. The browser leaves out disabled controls and controls without a name attribute. Check those attributes if a submitted value is missing. See MDN’s FormData and form controls for this form-based pattern.

Let the browser set the multipart header

Do not set Content-Type: multipart/form-data yourself when sending a FormData body. The browser creates the multipart body and a boundary value, then adds the boundary as a parameter in the Content-Type header. The boundary tells the server where one field ends and the next begins. If your code sets the header without the matching boundary, the server may not be able to read the body. MDN warns against setting this header for a FormData request.

Keep the Fetch options focused on the method and body:

await fetch("/uploads", {
  method: "POST",
  body: data,
});

Validate files and limits on the server

Browser checks can give users faster feedback, but they cannot enforce upload rules. A user can bypass JavaScript restrictions and send a request directly. The server must check every upload before storing or processing the file. OWASP recommends deciding which file types the service needs and testing how the server handles them. Its upload security guidance also warns that checking file extensions alone does not stop malicious content.

Treat the filename and the multipart part’s Content-Type as hints supplied by the client, not proof that the file is safe. A client can change both. The server should allow only file types the feature needs, inspect each file based on its expected format, and scan uploads for malware when the file types and processing steps call for it. File formats pose different risks. For example, when the server extracts an archive, it needs protections against paths that escape the intended directory and compressed files that expand until they use up disk space or memory.

Set a maximum size for each file and for the full request. The request limit also covers multipart fields and encoding overhead. Enforce both limits at the upload endpoint, and check the limits on any proxy, web server, or runtime in front of it. No single size is safe for every feature. Choose limits based on what the feature needs and the storage and processing capacity available. If a request exceeds a limit, return a clear client error instead of sending the oversized upload for further processing.

More in Web development Back to top ↑