How-To Guide

How to Upload Files with Progress in React

Build an accessible React upload component with drag-and-drop, progress, cancellation, validation, previews, and server-side safeguards.

On this page

  1. Introduction
  2. Build the upload surface
  3. Validate before uploading
  4. Upload with progress and cancellation
  5. Render honest states
  6. Server-side safeguards
  7. Test the component
  8. Common pitfalls
  9. Conclusion

Introduction

A file upload control looks simple: choose a file, send it, show a result. In practice it has more states than most forms. The user may drag a file, cancel halfway through, lose connectivity, pick a file that is too large, or select the same file twice. The browser exposes different APIs for each concern, and the server must enforce every limit the client claims to enforce.

This tutorial builds a single-file upload component in React with drag-and-drop, an accessible file input, upload progress, cancellation, previews for images, and clear error states. It uses XMLHttpRequest because its upload progress events are broadly supported. The same structure extends to multiple files with a queue, but a single-file flow makes the state transitions easier to reason about first.

Build the upload surface

Start with a real file input. A hidden input triggered by a div is a common source of keyboard and screen-reader problems. Use a visible input or associate a label with the input, and make the drop zone a button-like control that delegates to it:

import { useRef, useState } from 'react';

type UploadState =
  | { status: 'idle' }
  | { status: 'uploading'; progress: number }
  | { status: 'success'; url: string }
  | { status: 'error'; message: string };

export function FileUpload() {
  const inputRef = useRef<HTMLInputElement>(null);
  const [state, setState] = useState<UploadState>({ status: 'idle' });
  const [dragging, setDragging] = useState(false);

  return (
    <section aria-labelledby="upload-heading">
      <h2 id="upload-heading">Upload a file</h2>
      <div
        onDragEnter={(event) => {
          event.preventDefault();
          setDragging(true);
        }}
        onDragOver={(event) => event.preventDefault()}
        onDragLeave={(event) => {
          if (event.currentTarget === event.target) setDragging(false);
        }}
        onDrop={(event) => {
          event.preventDefault();
          setDragging(false);
          const file = event.dataTransfer.files[0];
          if (file) startUpload(file);
        }}
        data-dragging={dragging}
      >
        <p>Drag a file here, or choose one from your device.</p>
        <input
          ref={inputRef}
          type="file"
          accept="image/png,image/jpeg,application/pdf"
          onChange={(event) => {
            const file = event.target.files?.[0];
            if (file) startUpload(file);
          }}
        />
      </div>
      <UploadStatus state={state} />
    </section>
  );
}

onDragOver must call preventDefault, otherwise the browser refuses the drop. The onDragLeave check on currentTarget === target prevents flicker when the pointer moves over child elements. Drag-and-drop is an enhancement, not the only path: the file input remains usable with a keyboard and on touch devices.

Validate before uploading

Client-side validation exists to give fast feedback, not to secure the server. Check the declared MIME type and size, and return a message that explains the limit:

const MAX_BYTES = 10 * 1024 * 1024;
const ALLOWED_TYPES = ['image/png', 'image/jpeg', 'application/pdf'];

function validateFile(file: File): string | null {
  if (!ALLOWED_TYPES.includes(file.type)) {
    return 'Choose a PNG, JPEG, or PDF file.';
  }
  if (file.size === 0) return 'The file is empty.';
  if (file.size > MAX_BYTES) return 'The file must be 10 MB or smaller.';
  return null;
}

file.type comes from the operating system and can be wrong or empty. The server must inspect the file signature (magic bytes) and enforce its own size limit while reading the stream. A client that sends a 50 MB file directly with curl never runs your React validation.

For images, generate a preview with URL.createObjectURL and revoke it when the file changes or the component unmounts. Object URLs retain memory until revoked:

function usePreview(file: File | null): string | null {
  const [url, setUrl] = useState<string | null>(null);

  useEffect(() => {
    if (!file || !file.type.startsWith('image/')) {
      setUrl(null);
      return;
    }
    const next = URL.createObjectURL(file);
    setUrl(next);
    return () => URL.revokeObjectURL(next);
  }, [file]);

  return url;
}

Do not render the object URL in an img without a cleanup path. In a long-lived session with many uploads, leaked object URLs are a real memory problem.

Upload with progress and cancellation

XMLHttpRequest reports bytes sent through the upload progress event. Guard on lengthComputable; some proxies and browser combinations do not provide a total. Reset the input after a successful upload so selecting the same file fires change again:

function startUpload(file: File) {
  const validationError = validateFile(file);
  if (validationError) {
    setState({ status: 'error', message: validationError });
    return;
  }

  const request = new XMLHttpRequest();
  const body = new FormData();
  body.append('file', file);

  request.upload.addEventListener('progress', (event) => {
    if (!event.lengthComputable) return;
    const progress = Math.round((event.loaded / event.total) * 100);
    setState({ status: 'uploading', progress });
  });

  request.addEventListener('load', () => {
    if (request.status >= 200 && request.status < 300) {
      const result = JSON.parse(request.responseText) as { url: string };
      setState({ status: 'success', url: result.url });
      if (inputRef.current) inputRef.current.value = '';
    } else {
      setState({ status: 'error', message: `Upload failed (${request.status}).` });
    }
  });

  request.addEventListener('error', () => {
    setState({ status: 'error', message: 'Network error during upload.' });
  });

  request.addEventListener('abort', () => {
    setState({ status: 'idle' });
  });

  request.open('POST', '/api/upload');
  request.send(body);
}

Keep the request in a ref if you offer a cancel button:

const requestRef = useRef<XMLHttpRequest | null>(null);

function cancelUpload() {
  requestRef.current?.abort();
  requestRef.current = null;
}

Abort on unmount as well. Otherwise a completed request tries to set state on an unmounted component, and the network transfer continues even though the user navigated away. The abort event is also the right place to clear the progress bar; do not leave it stuck at 63 percent.

Render honest states

The UI should distinguish idle, uploading, success, and failure. Use the native progress element with a text label so assistive technology can report the value, and put asynchronous messages in an aria-live region:

function UploadStatus({ state }: { state: UploadState }) {
  if (state.status === 'uploading') {
    return (
      <div>
        <progress value={state.progress} max={100} aria-label="Upload progress" />
        <span>{state.progress}%</span>
        <button type="button" onClick={cancelUpload}>Cancel</button>
      </div>
    );
  }

  if (state.status === 'success') {
    return <p role="status">Upload complete. <a href={state.url}>Open file</a></p>;
  }

  if (state.status === 'error') {
    return <p role="alert">{state.message}</p>;
  }

  return null;
}

Use role="alert" for errors that require attention and role="status" for completion messages. Avoid replacing the entire form with a spinner; users should still see which file they selected and be able to retry.

Server-side safeguards

The server is the security boundary. A production upload endpoint should:

  • Enforce a maximum size while streaming, not after reading the entire body into memory. Reject early when the limit is exceeded.
  • Validate the file signature, not only Content-Type or the filename extension.
  • Generate a new storage filename and never join a user-supplied path onto a directory. Reject traversal sequences and null bytes.
  • Store uploads outside the web root or in object storage, and serve them through a controlled handler or signed URL.
  • Set a restrictive Content-Type and Content-Disposition when serving user files to avoid HTML or script execution in the origin.
  • Scan untrusted files for malware if the product allows public distribution.
  • Require authentication and CSRF protection for cookie-based sessions. Do not accept a bearer token in a query string, where it leaks into logs and referrers.
  • Record the uploader, byte size, detected type, and storage key for auditing and cleanup.

A PDF or image can still contain active content. Serving user uploads from the main application origin gives that content access to the same origin unless the response is isolated. A separate download domain or Content-Security-Policy: sandbox is a stronger boundary.

Test the component

With Playwright, set a file on the input and assert the visible states. Intercept the upload route so the test does not depend on a backend:

test('uploads a file and shows success', async ({ page }) => {
  await page.route('**/api/upload', async (route) => {
    await route.fulfill({
      status: 200,
      contentType: 'application/json',
      body: JSON.stringify({ url: '/files/report.pdf' }),
    });
  });

  await page.goto('/upload');
  await page.setInputFiles('input[type=file]', {
    name: 'report.pdf',
    mimeType: 'application/pdf',
    buffer: Buffer.from('%PDF-1.4 test'),
  });

  await expect(page.getByRole('status')).toContainText('Upload complete');
});

Add tests for an oversized file, a rejected type, and a 500 response. If you need to test progress events, mock XMLHttpRequest in a unit test; real network timing is too variable for a deterministic assertion. Test drag-and-drop separately by dispatching a drop event with a DataTransfer containing a file, and keep the file-input path as the primary regression test because it is the accessible path.

Common pitfalls

  • Forgetting preventDefault on dragover. The browser opens the file instead of firing drop.
  • Using accept as validation. It filters the picker, not the request.
  • Trusting the filename. Names can contain traversal sequences, control characters, and misleading extensions.
  • Reading the whole upload into memory. Use streaming and enforce limits incrementally.
  • Leaving object URLs unrevoked. Preview memory grows with every selection.
  • Not resetting the input. The same file cannot be selected twice without clearing the value.
  • Ignoring lengthComputable. Dividing by an unavailable total produces NaN.
  • Setting state after unmount. Abort the request and guard the cleanup path.

Conclusion

A reliable React upload component is mostly about state discipline: validate early for feedback, enforce everything again on the server, expose progress and cancellation honestly, and clean up requests and object URLs. XMLHttpRequest remains the pragmatic choice for upload progress in the browser. Once the single-file flow is correct, adding a queue for multiple files is a matter of tracking one request and one state object per item.

Sources: MDN XMLHttpRequest, MDN FormData, OWASP File Upload Cheat Sheet.

FAQ

Why use XMLHttpRequest instead of fetch for upload progress?
XMLHttpRequest exposes upload progress events in all current browsers. fetch can stream a request body in some environments, but browser support for upload progress on request streams is limited. XHR also provides a simple abort method.
Can the accept attribute replace server-side validation?
No. accept is a hint to the file picker and can be bypassed by renaming a file or sending a direct request. The server must validate size, declared type, and file signatures, and must never trust the client-supplied filename.
How do I let the user select the same file twice?
Clear the input value after a successful upload, for example by setting inputRef.current.value to an empty string. Otherwise the change event does not fire when the same path is selected again.

Related Examples