← All posts

JavaScript File Upload with fetch and FormData: Validation, Image Preview and a Real Progress Bar

Upload a file without reloading the page, properly: FormData, type and size checks, image preview, a reliable progress bar and PHP handling, plus the traps behind an empty $_FILES array.

JavaScript File Upload with fetch and FormData: Validation, Image Preview and a Real Progress Bar

Key points

  • FormData builds the multipart request for you: never set the Content-Type header yourself.
  • Check type and size in the browser to help the user, but repeat every check on the server.
  • fetch doesn’t report upload progress: for a dependable progress bar, XMLHttpRequest is still the right tool.

Uploading a file without a page reload is one of the most common requests on our projects: a profile picture, a supporting document in a customer portal, a CSV import in a back office. The basic code is short, but problems show up fast: an empty array on the server, a size limit with no clear message, users with no idea whether the upload is progressing. Here’s a complete implementation, browser and server side, covering the pitfalls we run into most.

The minimal upload with fetch and FormData

Start from a real HTML form with action, method and enctype. It keeps working if JavaScript fails to load, and it’s the single source of truth for the endpoint and the fields:

<form id="proof-form" action="/api/documents" method="post" enctype="multipart/form-data">
  <label for="file">Supporting document (PDF, JPG or PNG, 10 MB max)</label>
  <input type="file" id="file" name="file" accept=".pdf,.jpg,.jpeg,.png" required>
  <img id="preview" alt="" hidden>
  <input type="hidden" name="case_id" value="1284">
  <progress id="bar" max="1" value="0"></progress>
  <button type="submit">Upload</button>
  <p id="message" role="status"></p>
</form>
const form = document.querySelector('#proof-form');
const message = document.querySelector('#message');

form.addEventListener('submit', async (event) => {
  event.preventDefault();
  const data = new FormData(form); // the file AND every other named field

  try {
    // Do NOT set Content-Type: the browser writes it, boundary included
    const response = await fetch(form.action, { method: 'POST', body: data });
    if (!response.ok) {
      throw new Error(`HTTP error ${response.status}`);
    }
    const result = await response.json();
    message.textContent = `File received: ${result.name}`;
  } catch (error) {
    message.textContent = 'Upload failed, please try again.';
    console.error(error);
  }
});

new FormData(form) collects every field that has a name attribute, including the selected file. Three mistakes come up again and again:

  • Setting Content-Type manually. A multipart request needs a “boundary” separating its parts, and the browser generates it. Write 'Content-Type': 'multipart/form-data' yourself and the boundary is missing, so the server finds no file. It’s the number one cause of the empty $_FILES arrays we get asked to debug.
  • Sending the file as JSON. JSON.stringify() turns a File object into {}. Files travel as multipart, not JSON.
  • Forgetting that fetch doesn’t reject on HTTP errors. A 413 or 500 response lands in your try block: check response.ok before reading the body.

Validating the file before upload, with a preview

The accept attribute only filters the file picker: users can switch to “All files” or drop anything they like. Checking type and size on selection saves them from waiting for a long upload only to have the file rejected:

const input = document.querySelector('#file');
const preview = document.querySelector('#preview');
const MAX_SIZE = 10 * 1024 * 1024; // 10 MB: same value as on the server
const TYPES = ['application/pdf', 'image/jpeg', 'image/png'];

input.addEventListener('change', () => {
  const file = input.files[0];
  input.setCustomValidity('');
  if (preview.src) URL.revokeObjectURL(preview.src);
  preview.hidden = true;
  if (!file) return;

  if (!TYPES.includes(file.type)) {
    input.setCustomValidity('Accepted formats: PDF, JPG or PNG.');
  } else if (file.size > MAX_SIZE) {
    input.setCustomValidity('The file is larger than 10 MB.');
  } else if (file.type.startsWith('image/')) {
    preview.src = URL.createObjectURL(file); // local preview, nothing is uploaded
    preview.hidden = false;
  }
  input.reportValidity();
});

setCustomValidity() plugs your check into native form validation: as long as the message isn’t empty, the browser blocks submission and shows the error next to the field, with no extra code. For the preview, URL.createObjectURL() is lighter than reading the file as base64 with FileReader, as long as you release the URL with revokeObjectURL() when the selection changes.

One caveat: file.type is guessed by the browser from the extension, and can even be empty. It’s a convenience for the user, never a guarantee. The real check happens on the server, against the file’s actual content.

Showing a progress bar: where fetch falls short

fetch has no upload progress events. Streaming request bodies, which would let you measure what’s been sent, aren’t supported consistently across browsers. For a progress bar that works everywhere, the tool is still XMLHttpRequest, wrapped in a promise so the calling code stays readable:

function uploadWithProgress(url, data, onProgress) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', url);

    xhr.upload.addEventListener('progress', (e) => {
      if (e.lengthComputable) onProgress(e.loaded / e.total);
    });
    xhr.addEventListener('load', () => {
      if (xhr.status >= 200 && xhr.status < 300) resolve(JSON.parse(xhr.responseText));
      else reject(new Error(`HTTP error ${xhr.status}`));
    });
    xhr.addEventListener('error', () => reject(new Error('Network error')));
    xhr.addEventListener('abort', () => reject(new DOMException('Upload cancelled', 'AbortError')));

    xhr.send(data);
  });
}

// Inside the submit handler, instead of fetch()
const bar = document.querySelector('#bar');
const result = await uploadWithProgress(form.action, new FormData(form), (ratio) => {
  bar.value = ratio;
  if (ratio === 1) message.textContent = 'Processing…';
});

A detail that changes the experience: progress hits 100% when the file has reached the server, not when the server has finished with it. If you resize images, parse a PDF or import a CSV, the response can take several more seconds. Without a “Processing” message, users stare at a full bar where nothing happens, and upload the file again.

Tokens (a WordPress nonce, a CSRF token) go in with xhr.setRequestHeader() between open() and send().

Server side: receiving the file in PHP without surprises

Here’s a minimal but complete endpoint that always answers with JSON and a meaningful HTTP status:

<?php
header('Content-Type: application/json');

// Body larger than post_max_size: PHP empties $_POST and $_FILES with no other signal
if (empty($_FILES) && (int) ($_SERVER['CONTENT_LENGTH'] ?? 0) > 0) {
    http_response_code(413);
    exit(json_encode(['error' => 'File too large.']));
}

$file = $_FILES['file'] ?? null;
if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400); // the UPLOAD_ERR_* code tells you why
    exit(json_encode(['error' => 'Missing or incomplete file.', 'code' => $file['error'] ?? UPLOAD_ERR_NO_FILE]));
}

// The real type, read from the content: never the one the browser announced
$type = (new finfo(FILEINFO_MIME_TYPE))->file($file['tmp_name']);
$extensions = ['application/pdf' => 'pdf', 'image/jpeg' => 'jpg', 'image/png' => 'png'];
if (!isset($extensions[$type])) {
    http_response_code(415);
    exit(json_encode(['error' => 'Format not accepted.']));
}

// Random name, folder outside the web root
$id = bin2hex(random_bytes(16)) . '.' . $extensions[$type];
if (!move_uploaded_file($file['tmp_name'], '/var/storage/documents/' . $id)) {
    http_response_code(500);
    exit(json_encode(['error' => 'Could not save the file.']));
}

echo json_encode(['id' => $id, 'name' => $file['name']]);

Two PHP settings cap the size: upload_max_filesize per file and post_max_size per request. The second catches everybody out: when exceeded, it silently empties $_POST and $_FILES, hence the CONTENT_LENGTH check.

The web server usually has its own limit too (client_max_body_size in Nginx). When that one is hit, Nginx answers 413 with an HTML page before PHP even runs, and response.json() fails with a baffling syntax error. Check the status before parsing, and align all three limits with the one announced in the form.

In production, add a permission check on the record and CSRF protection; our article on secure file uploads in PHP covers both.

Multiple files, drag and drop, and cancelling

For several files, add the multiple attribute and name the field files[]. A drop zone must call preventDefault() on dragover (otherwise the browser opens the file instead of dropping it), then build its own FormData from e.dataTransfer.files. Always keep the regular file input alongside it: drag and drop doesn’t exist for keyboard users or on most phones.

On the PHP side, $_FILES['files'] holds an array of name, an array of tmp_name and an array of error, not a list of files: loop over the indexes and run the earlier checks on each. For a Cancel button, call xhr.abort(): the promise rejects with an AbortError, so you can tell it apart from a real failure.

FAQ

Why is $_FILES empty when the file was clearly sent?

In order of frequency: a Content-Type header set by hand in your JavaScript, a request larger than post_max_size, a file input with no name attribute, or a form submitted without JavaScript and without enctype="multipart/form-data".

Can fetch track upload progress?

Not reliably across browsers today. fetch lets you track a download by reading response.body chunk by chunk, but not an upload. For an upload progress bar, use XMLHttpRequest and its upload.progress event.

A document upload in your customer portal, file imports in your app or back office that need to be more reliable? We build robust, secure upload flows on both the browser and the server side.

Share LinkedIn Facebook X WhatsApp
</>

webtestudio

Web agency: custom WordPress sites, premium themes and SaaS software.

Discuss your project →