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

To upload a file without navigating away, intercept a form’s submit event, build a FormData object from the form, and send it in a POST request to an endpoint that accepts multipart/form-data. Use Fetch for a straightforward request and response; use XMLHttpRequest when the interface needs upload-progress events.

Set up the file form

Give the file input a name; that name identifies the file part sent to the server. Include enctype="multipart/form-data" so the form also works as a regular browser submission if JavaScript is unavailable. The server route must be configured to accept and parse multipart form data.

<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>

To let the user select more than one file, add multiple to the file input. The server must also support receiving and handling multiple file parts.

Upload with Fetch

In the submit handler, prevent the default page navigation and pass the form to new FormData(form). The resulting object includes the selected file and other successful form controls, such as named text inputs. Send it as the body of a POST request:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
const form = document.querySelector("#upload-form");
const result = document.querySelector("#upload-result");

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

  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);
  }
});

Do not set the request’s Content-Type header yourself. The browser must add the multipart boundary that separates parts in the request body. MDN’s FormData guidance specifically warns against explicitly setting this header when submitting FormData with Fetch or XMLHttpRequest.

Check response.ok or the response status: Fetch resolves its promise for HTTP error responses such as 400 or 500, so a rejected promise alone does not cover all failures. The example reports success when the server returns a successful HTTP status; adapt it to read a response body if the endpoint returns details or a stored-file URL.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Show upload progress with XMLHttpRequest

Fetch accepts FormData for uploads, but if the interface needs transfer-progress notifications, use the upload event target on an XMLHttpRequest. A progress event reports transferred bytes; it does not prove that the server has validated or stored the file.

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", (event) => {
    if (event.lengthComputable) {
      const percent = Math.round((event.loaded / event.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 during upload.";
  });

  request.addEventListener("abort", () => {
    result.textContent = "Upload canceled.";
  });

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

Register upload listeners before sending. MDN notes browser bugs concerning whether upload listeners need to be attached before or after open(); if exact event timing matters, test the browsers your application supports. See MDN’s XMLHttpRequest upload property documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

What the server must do

The browser sends file bytes as a multipart part; the server endpoint must parse that request and apply the application’s rules. FormData carries the actual selected File, not merely a filename string. Client-side checks can improve feedback, but they cannot be the security boundary.

  • Set size and file-type limits appropriate to the application, then validate uploads on the server.
  • Store files in a dedicated location, preferably outside the application directory tree, and disable execute permissions there where possible.
  • Do not use the submitted filename as a storage path. Treat filenames and file contents as untrusted; encode a filename appropriately if displaying it or writing it to logs.
  • Use the multipart parsing and binding mechanism for your backend. For example, Microsoft’s ASP.NET Core 10.0 guide uses IFormFile; that framework-specific type is not a general browser or server API.

Microsoft’s ASP.NET Core 10.0 upload guide covers multipart forms, multiple uploads, server handling, and security considerations. The Fetch Standard describes the request and FormData model.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Choose Fetch or XMLHttpRequest

Need Choose Why
Send FormData and handle the server response Fetch It accepts FormData as a request body and supports a simple promise-based flow.
Show transfer progress XMLHttpRequest Its upload object exposes progress events.
Support a particular older browser set Verify compatibility for those browsers Browser-version support is not established here; test the targets you actually support.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting Ajax file uploads

  • The server says no file was received: Confirm the file input has a name, the user selected a file, and the server parser expects the same multipart field name. Ensure the route accepts multipart form data.
  • The request fails after manually setting Content-Type: Remove the explicit Content-Type: multipart/form-data header and let the browser generate it with the boundary.
  • The page reloads instead of uploading asynchronously: Confirm the submit listener is attached to the right form and calls event.preventDefault().
  • The UI reports success for a rejected upload: Check the HTTP status. With Fetch, inspect response.ok; with XMLHttpRequest, check the status in the load handler.
  • Progress does not appear: Check that the upload listener is attached before send(), and confirm that progress events are available in the target browsers. A percentage can be calculated only when lengthComputable is true.
  • Multiple selection works in the picker but not on the server: Add multiple to the input and ensure the endpoint and its multipart parser handle multiple file parts.
  • A valid-looking file is rejected or unsafe to store: Browser-side file checks are only a convenience. Apply the relevant type, size, and storage controls on the server.

Or skip the browser setup

If your goal is to capture a website rather than build a file-upload feature, ScreenshotNeo is a website screenshot API and MCP server. A GET request can return a PNG, JPEG, WebP, or PDF. For example, this cURL request saves a WebP screenshot:

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
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 documentation for API options. Cookie banners, newsletter popups, and chat widgets are removed before capture; bot checks, blank pages, failed loads, and cache hits are not billed. Its MCP server lets AI agents take screenshots. The Free plan includes 1,000 screenshots per month with no card, and paid plans start at $5 for 3,000 screenshots. Sign up for 1,000 free screenshots a month, with no card required.

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.