October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How to Upload Files With Ajax Using Fetch or XMLHttpRequest

Use FormData to send files asynchronously with Fetch, or XMLHttpRequest when you need progress events. Learn the multipart-header rule, server safeguards, and common fixes.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To upload a file without navigating away from the page, submit a form’s FormData in a POST request. Use Fetch for a simple request-and-response flow; use XMLHttpRequest (XHR) if you need upload-progress events. In either case, leave the multipart Content-Type header unset so the browser can add the required boundary. The server must parse the multipart request and validate and safely store the uploaded content.

Build the upload form

Give the file input a name; that name becomes the multipart field the server reads. Setting action, method and enctype also leaves the form configured for a normal browser submission if JavaScript is unavailable.

As an Amazon Associate I earn from qualifying purchases.

<form id="upload-form" action="/upload" method="post" enctype="multipart/form-data">
  <label for="upload-file">Choose a file</label>
  <input id="upload-file" name="file" type="file" required>
  <button type="submit">Upload</button>
</form>
<output id="upload-result" aria-live="polite"></output>

Replace /upload with your application’s upload endpoint. A selected file is available from the input as a File object; a filename string by itself is not the file’s contents.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Upload with Fetch

Construct FormData from the form in its submit handler, prevent the default navigation, and pass the data as the request body. The browser encodes it as multipart form data.

#1 Best Overall
Sale
Lexar D40E 128GB Dual USB 3.2 Gen 1 Type-C Jump Drive, Champagne Silver
  • USB-C 2-in-1 storage OTG: The Lexar JumpDrive Dual Drive D40E features USB Type-A and Type-C connectors in a slim, portable form factor for easy device compatibility
  • Transfer speeds up to 100MB/s: Based on internal testing, performance may vary depending upon the host device, interface, and usage conditions. 1MB=1,000,000 bytes
  • Plug and Play: Widely compatible with USB Type-C smartphones, tablets, laptops, Macs, and traditional Type-A devices, no software installation required. The 360° swivel design allows for easy switching between connectors without the hassle of losing a cap
  • Durable & Compact: The Lexar D40E USB memory stick features a metal enclosure, withstands temperatures from 0° to 50° C (32°F to 122°F), and is lightweight at 26g with dimensions of 70.4 x 16.9 x 11.7mm
  • Security & Warranty: Securely protects files using an advanced security software solution with 256-bit AES encryption. Backed by a Lexar 3-year limited warranty
const form = document.querySelector("#upload-form");
const result = document.querySelector("#upload-result");

form.addEventListener("submit", async (event) => {
  event.preventDefault();
  const body = new FormData(form);

  try {
    const response = await fetch(form.action, {
      method: "POST",
      body
    });
    if (!response.ok) throw new Error(`Upload failed: ${response.status}`);
    result.textContent = "Upload complete.";
  } catch (error) {
    result.textContent = "Upload failed. Please try again.";
    console.error(error);
  }
});

The success message means the endpoint returned an HTTP success status; the server should return that status only after its own validation and handling have succeeded. If the endpoint returns useful response data, read it from response and display an appropriate result.

Do not set Content-Type yourself. In particular, do not set it to multipart/form-data manually: the browser must include the multipart boundary parameter. MDN Web Docs gives this guidance for FormData requests made with Fetch or XMLHttpRequest: Using FormData Objects.

Rank #2
KOOTION USB C Flash Drive 32GB 2 in 1 OTG USB 3.0/Type C Thumb Drive Dual Drive USB C Memory Stick for Smartphone Laptop Tablet PC, Blue
  • 2 in 1: USB C + USB 3.0, 32GB usb c flash drive has dual ports, usb 3.0 port is applied to all devices which have usb 3.0 interface and usb c port is widely used in all Android smartphones with OTG function
  • High Speed USB 3.0: Read speed up to 90 MB/s, Write speed up to 30 MB/s, the speed of USB 3.0 interface is faster than USB 2.0, save time to wait, increases work productivity. Note: Speed will be limited if you use the USB key in the USB 2.0 interface
  • Large Compatibility: The USB 3.0 Connector is compatible with USB 3.0 & USB 2.0 backward USB 1.1 devices, such as Laptop, Desktop, Car Audio, Tablet, TV, Speakers, Projector. USB-C port is compatible with all Android Smartphones
  • Expand Storage: Good performance in storing, transferring and sharing digital data with families, friends, colleagues, customers. It can expand the capacity of smartphone, you can watch movies or share pictures when you go on vacation with your family
  • Note: Make sure your smartphone is equipped with OTG function and need to open OTG function in Settings when you plug memory stick, then you can transfer easily data bewteen different devices

Show upload progress with XMLHttpRequest

Fetch accepts FormData, but for transfer-progress notifications use the XHR upload event target. This example reports a percentage when the browser can calculate one, and treats transfer completion separately from the server’s response.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const form = document.querySelector("#upload-form");
const result = document.querySelector("#upload-result");

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const request = new XMLHttpRequest();
  const body = new FormData(form);

  request.upload.addEventListener("progress", (progressEvent) => {
    if (progressEvent.lengthComputable) {
      const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100);
      result.textContent = `Uploading: ${percent}%`;
    } else {
      result.textContent = "Uploading…";
    }
  });

  request.addEventListener("load", () => {
    if (request.status >= 200 && request.status < 300) {
      result.textContent = "Upload complete.";
    } else {
      result.textContent = `Upload failed: ${request.status}`;
    }
  });
  request.addEventListener("error", () => {
    result.textContent = "Network error while uploading.";
  });
  request.addEventListener("abort", () => {
    result.textContent = "Upload canceled.";
  });

  request.open("POST", form.action);
  request.send(body);
});

Progress reaching 100% only indicates that the browser has finished sending the request body; it does not establish that the server accepted, validated or stored the file. Wait for the request’s response before showing success. MDN notes browser bugs concerning whether upload event listeners need to be attached before or after open(); if precise event timing matters, test the browsers you support. See MDN’s XMLHttpRequest upload property reference.

Rank #3
Sale
Lexar D40E 64GB Dual USB 3.2 Gen 1 Type-C Jump Drive, Champagne Silver
  • USB-C 2-in-1 storage OTG: The Lexar JumpDrive Dual Drive D40E features USB Type-A and Type-C connectors in a slim, portable form factor for easy device compatibility
  • Transfer speeds up to 100MB/s: Based on internal testing, performance may vary depending upon the host device, interface, and usage conditions. 1MB=1,000,000 bytes
  • Plug and Play: Widely compatible with USB Type-C smartphones, tablets, laptops, Macs, and traditional Type-A devices, no software installation required. The 360° swivel design allows for easy switching between connectors without the hassle of losing a cap
  • Durable & Compact: The Lexar D40E USB memory stick features a metal enclosure, withstands temperatures from 0° to 50° C (32°F to 122°F), and is lightweight at 26g with dimensions of 70.4 x 16.9 x 11.7mm
  • Security & Warranty: Securely protects files using an advanced security software solution with 256-bit AES encryption. Backed by a Lexar 3-year limited warranty

Choose Fetch or XMLHttpRequest

Need Use Reason
Send FormData and handle the response Fetch It accepts FormData as a request body and suits a straightforward asynchronous request/response flow.
Display transfer progress XMLHttpRequest Its upload object exposes progress events.
Support a particular set of older browsers Check compatibility for those browsers Browser-version support is not established here; verify it against your actual targets.

Fetch is not limited to non-file requests: it can send FormData containing files. The practical distinction here is progress reporting.

Handle multiple files and other fields

To let a user select more than one file, add multiple to the file input. Keep a field name your endpoint expects, and ensure the endpoint is implemented to accept and process multiple file parts.

Rank #4
2-Pack 128GB USB C Flash Drive Dual Type C + USB A Memory Stick Jump Drive 2-in-1 Thumb Drive for Storage and Backup (128GB*2 Black&Blue)
  • 2-in-1 Dual Design: Features both USB-C and USB-A connectors, making it compatible with phones, tablets, MacBooks, PCs, and laptops-no adapter needed
  • Wide Compatibility: Works seamlessly with USB A and USB C devices, ensuring reliable file transfers across smartphones, computers, and more
  • Ample Storage Options: Available in 16GB/32GB/64GB/128GB providing plenty of space for photos, videos, music, and documents
  • Portable & Lightweight: Compact and durable design for travel, school, or daily use-take your files anywhere
  • Plug-and-Play Convenience: No software or drivers required; simply insert into USB-C or USB-A ports and start transferring files instantly
<input id="upload-files" name="files" type="file" multiple>

Creating new FormData(form) includes the selected files and other successful form controls, such as named text inputs. The browser APIs represent form entries and file parts in the multipart request; the server must parse those parts using its own framework or library. The WHATWG Fetch Standard describes the FormData and multipart model.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Validate and store uploads on the server

The browser-side code transports data; it does not make an upload safe. Treat both file contents and submitted filenames as untrusted. Apply application-appropriate size and type policies and validate on the server, even if the page also checks files for user convenience.

Best Value
Samsung Type-C USB Flash Drive 256GB, USB 3.2 Gen 1, Up to 400MB/s
  • USB-C STORAGE ON THE GO: This sleek drive is supported by Samsung NAND flash and is incredibly compact to fit in the palm of your hand; Count on reliable performance and fast transfer speeds while staying compact
  • PERFORMANCE WITH SPEED: No need to choose between performance and reliability; Experience a fast, powerful flash drive that transfers 4GB files in just 11 seconds with up to 400MB/s USB 3.2 Gen 1 read speeds and is backward compatible with USB 3.0/2.0
  • MODERN MEETS ICONIC: The ultra-sleek USB-C drive looks as good as it performs; Featuring a reversible plug, the Type-C inserts into your devices seamlessly every time; Transfer large files with style and ease
  • ALWAYS CONNECTED: USB-C is compatible across devices, including laptops, tablets, phones and cameras, with enough space for 63,730 photos or maximum 12 hours of 4K video; With up to 256GB of storage space, this pocket-sized thumb drive comes in handy wherever you go
  • TOUGH & TRUSTED: Files stay secure, no matter the terrain; Samsung's flash memory technology makes the Type-C a trustworthy drive to store your valuable data; It's waterproof, shock-proof, magnet-proof, temperature-proof, and X-ray-proof body, plus it's backed by a 5-year limited warranty
  • Use a dedicated upload location, preferably outside the application directory tree, and disable execute permissions there.
  • Do not use a client-supplied filename as a storage path. Submitted names may contain full or relative paths; generate a safe storage name instead.
  • If you display or log an original filename, encode it appropriately for that context.
  • Make sure the backend’s multipart parser and request-size limits are configured for the files your application intends to accept.

Server APIs vary by framework. For example, Microsoft’s ASP.NET Core 10.0 file upload guide shows multipart forms and access to uploaded files through IFormFile; that type is specific to ASP.NET Core, not a universal upload API. Apply the equivalent parsing and safe-storage approach in your own backend.

Troubleshooting common upload failures

  • The server says no file was received: Confirm the input has a name, a file is selected, the request is sent to the intended endpoint, and that endpoint parses multipart form data. Check that its expected field name matches the input’s name.
  • The server cannot parse the multipart body: If you set a Content-Type header manually, remove it and let the browser generate the header and boundary for the FormData body.
  • The request returns an error status: Check the endpoint’s response and server logs for its validation, authentication, size-limit or parsing error. The example treats non-2xx responses as failures; a completed transfer is not enough to show success.
  • No progress percentage appears: The percentage is only calculated when the XHR progress event has lengthComputable set to true. Display an indeterminate “Uploading” state otherwise.
  • Progress completes but the upload fails: Progress reports bytes sent, not server-side acceptance. Handle the response, network error and abort outcomes separately.
  • The page navigates instead of using Ajax: Check that the submit listener is attached to the correct form and calls event.preventDefault(). Also verify that JavaScript has loaded without an earlier error.

Or skip the browser setup

ScreenshotNeo is a website screenshot API, not a file-upload endpoint; use the Ajax patterns above to upload user-selected files. If the separate task is capturing a website, one GET request returns an image or PDF:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API docs. ScreenshotNeo removes cookie banners, popups and chat widgets before capture; bot checks, blank pages and failed loads are never billed; an MCP server lets AI agents take screenshots; and 1,000 screenshots a month are free with no card, with paid plans starting at $5 for 3,000. Learn about ScreenshotNeo or sign up free for 1,000 screenshots a month with no card.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.