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.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteUpload 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
- 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
- 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.
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
- 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-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.
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
- 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-Typeheader 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
lengthComputableset 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:
Quick Recap
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.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchProduct 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.




