iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
To upload a file in React JS, put a labeled <input type="file"> in a form, create a FormData object when the form is submitted, and send it to a server endpoint with fetch. Selecting a file only gives the browser a file to work with; it does not send or store it. The example below uses /upload as an illustrative endpoint, so your server must provide a compatible route that accepts multipart form data.
What do you need before uploading a file?
You need a React form and a receiving endpoint on a server you control. The browser can let a person choose a file and send it, but a React component alone does not parse the request, decide who is allowed to upload, or store and serve the file. The example uses the field name file; the server must expect that same multipart field name.
- A labeled file input, such as
<input name="file" type="file">. - A submit handler that prevents the browser’s normal form navigation and creates
FormData. - A server route at the URL you submit to, configured to parse multipart form data and apply its own authorization, validation, and storage rules.
The /upload URL below is not a built-in React route. Replace it with the path your server exposes. React’s form documentation describes reading form data in an onSubmit handler as a way to submit data without relying on a function-valued form action: React form reference.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteThink of an upload as three separate stages: the user selects a file, the browser sends it in a request, and the server decides whether to accept and store it. A filename appearing beside the picker confirms only the first stage. It does not mean the request has been sent or that a server has saved anything.
Popular on Amazon
- 【90 Degree Full Function USB C Adapter】Supports the latest USB4 standard for up to 40Gbps of bandwidth, 8K video support, and up to 240W Fast charging; Support USB PD 3.1 Extended Power Range (EPR) including 140W, 180W and 240W. Your productivity is easily doubled. *Warm Tip: For the best fit, please make sure the USB-C port is fully exposed; thick or bulky cases may affect compatibility.
- 【Reliable Quality】Made from high-quality, scratch-resistant aluminum alloy, delicate metal frame. get excellent wear resistance and heat dissipation. Non-Slip Design for easier insertion and removal.
- 【Small and portable】Ultra thin size, ultra compact design, a petite physique that matches the minimalist design of your modern laptops. Coming with a slim figure that won't block the port next to the one it's plugged into.
- 【Compatibility】Widely work with most usb c, thunderbolt 4/3 devices. Compatibilit for ROG Ally, Steam Deck, Switch, MacBook Pro, Quest 3 VR headset, Surface Book 2, iPhone 18/17/16/15, Samsung Galaxy S23/S22/S21, Note 20/10, Google Pixel, ChromeBook, etc.
- 【Excellence Customer Support】If you experience any issues or cable failure, simply reach out to our dedicated customer service team. We provide a prompt response within 18 hours, providing you with the necessary technical support to resolve any concerns.
How do I upload a file in React JS?
Use the form’s submit event to gather the selected file and send it as the request body. This example shows a pending message and a success or error message; it does not calculate a percentage.
- Create a form with a labeled file input. Give the input a
name, because that name becomes the multipart field the server receives. - In the submit handler, call
preventDefault(), then constructnew FormData(form)from the form element. - Send the data with
fetch, usingPOSTand theFormDataobject as the body. - Check
response.okbefore treating the request as successful. Fetch can resolve normally for an HTTP error response, such as a server error.
import { useState } from 'react';
export default function FileUpload() {
const [status, setStatus] = useState('');
async function handleSubmit(event) {
event.preventDefault();
const form = event.currentTarget;
const formData = new FormData(form);
setStatus('Uploading…');
try {
const response = await fetch('/upload', {
method: 'POST',
body: formData,
});
if (!response.ok) {
throw new Error(`Upload failed: ${response.status}`);
}
setStatus('Upload complete.');
form.reset();
} catch (error) {
setStatus(error instanceof Error ? error.message : 'Upload failed.');
}
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="file">Choose a file</label>
<input id="file" name="file" type="file" required />
<button type="submit">Upload</button>
<p role="status">{status}</p>
</form>
);
}
The snippet illustrates React and browser APIs; it is not a claim that the code was run or that a particular server implementation is included. Its form uses required to ask the browser to require a selection before submission. That improves the form interaction but is not a substitute for server-side checks. The live status text announces state changes to assistive technology.
In the handler, event.currentTarget is the form that owns the submit event. Passing that form to FormData gathers its successful named controls at submission time, including the selected file. Calling preventDefault() keeps the browser from navigating away through a normal form submission, so the component can send the request and update its status itself. The endpoint still needs to accept the request and return an appropriate HTTP status.
After an OK response the sample calls form.reset(), which clears the form’s current values, including the file selection. If the upload fails, it leaves the selection in place so the user can retry. The status message is intentionally simple; a production interface can make errors clearer, but should not tell the user that a file was stored unless the server response confirms success.
Why the input is not controlled like a text field
A file picker is browser-controlled. Read the selection from the input’s files collection, or let FormData collect the named field. Do not try to put a local path or a chosen filename into React state and assign it to the input’s value. The file input’s value is not a usable filesystem path, and a page cannot set an arbitrary path on a user’s device. See the React input reference for the file-input behavior.
If you need to inspect a selection before sending it, read the browser-provided File object from input.files; for a single-file input, the first entry is commonly accessed as input.files[0]. That object is the file data the page is permitted to work with after the user chooses it. The string displayed by the picker is not a path that your component can use to open arbitrary files on the computer.
Why the request does not set Content-Type
Do not add a Content-Type: multipart/form-data header yourself when passing FormData to fetch. The browser must add the multipart boundary that separates fields in the request body; setting the header manually can omit or mismatch that boundary and prevent the server from parsing the upload. MDN’s guidance for FormData requests is explicit: do not explicitly set the Content-Type header.
Free tools Windows power users keep installed
One-click scans. No signup required.
This is an easy mistake when copying a JSON request example: FormData is not a JSON string, so do not stringify it or set a JSON content type for this request. Pass the object directly as body and let the browser construct the multipart request, including its boundary. Your server must then use a multipart-capable parser; an endpoint expecting JSON or a raw file body is not interchangeable with this form submission.
How do FormData and fetch work together?
FormData packages form entries—including a selected File—for a multipart request. fetch sends that package to the URL you specify; the server is responsible for receiving and handling it.
In new FormData(form), the form argument tells the browser to collect the form’s named controls. A file input named file arrives as a multipart entry named file, so the server’s parser must look for that name. Other named fields in the same form are collected too. Disabled controls are omitted from the data, so do not disable a value that the endpoint needs to receive.
Also popular on Amazon
- 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.
This makes a form useful when a request includes more than a file. For example, if the form also has a named description field, its value is included along with the file. The server must know which multipart names to read. A label alone does not create a submitted field name: use the input’s name attribute for data that should be part of the request.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →If the upload is not based on a form, you can create an empty object and append the selected file yourself:
const formData = new FormData();
formData.append('file', selectedFile);
const response = await fetch('/upload', {
method: 'POST',
body: formData,
});
Here, selectedFile should come from a browser-provided file selection, for example input.files[0]. The key passed to append is still the multipart field name your endpoint must accept. For a form with additional metadata, named fields can be collected from the form or appended explicitly, but the server must agree on the expected names.
Choose between the two patterns based on how the UI is built. new FormData(form) is convenient when a real form already contains the file input and other fields. new FormData() with append() is useful when you are assembling the request from values outside a form. They both produce form data; neither removes the need for the endpoint to accept multipart data and recognize the submitted field keys.
How do I upload multiple files in React?
Add the multiple attribute to the file input, then process each file from its files collection or retrieve every matching entry from FormData with getAll().
<input id="files" name="file" type="file" multiple />
When the form is submitted, new FormData(form) gathers the selected values under the input’s field name. To inspect every file under that name:
const files = formData.getAll('file');
By contrast, formData.get('file') returns only the first value for that field. Make the server’s multipart parser and field-name handling match the input. A client can submit several values, but the endpoint may impose its own count, size, or type limits.
The multiple attribute changes the picker so the user can choose more than one file; it does not guarantee that the server will accept all of them. Use the input’s files collection when you want to inspect the selected files directly, or use getAll('file') to retrieve all entries submitted under the matching multipart key. If the server expects a different field name, or is configured to accept only a particular upload shape, update the client and server together.
Also decide what the interface should do if one of several files is rejected. The browser example does not establish a batch-processing policy. The receiving endpoint defines its accepted types, limits, and response, and the UI should report that response accurately rather than assuming that selecting multiple files means every file was stored.
How do I validate a file safely?
Use browser-side constraints to guide a person, but make the server the authority on whether an upload is permitted. An accept attribute can filter the picker toward intended file types, but it does not prove that the selected content is safe or genuine.
Also popular on Amazon
- 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.
For example, this input guides the picker toward PNG and JPEG images:
<input name="file" type="file" accept="image/png,image/jpeg" />
The server should independently check the actual content and enforce the rules for the application. OWASP’s File Upload Cheat Sheet advises allowlisting needed extensions, not trusting the supplied Content-Type alone, generating stored filenames, applying size limits, checking authorization, and isolating uploaded content. Those are server responsibilities; none is implemented by the React form above.
- Allow only the file types and extensions the feature needs.
- Validate content beyond a browser-supplied MIME type, which can be spoofed.
- Enforce size limits and authorization before accepting or storing data.
- Use generated safe storage names rather than trusting a user’s filename.
- Store and serve uploads in a way that isolates untrusted content from the application.
These controls solve different problems. An extension allowlist limits the kinds of files the feature intends to handle; checking content avoids treating a supplied type label as proof; size limits control what the endpoint will accept; and authorization determines who may submit it. A generated storage name avoids using a user-chosen filename as the stored name, while isolation helps keep untrusted uploads separate from application content. A client-side accept filter or required attribute performs none of those server checks.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Do not treat browser validation as a security boundary. A user can send a request without using your page’s picker, so the endpoint must apply its own rules regardless of what attributes appear in the React component. The React example is the sending side of the flow, not an upload-security implementation.
Why isn’t my React file upload working?
Start by checking the boundary between the browser and the server: the input, request, endpoint, and parser must all agree. These common mismatches can make a form look correct while the server receives no usable file.
The server says the file field is missing
Confirm that the input has a name, and that its value matches the field name the server expects. If the input is named file, the server must parse the multipart field named file. With manually assembled data, use the same key in append.
For form-derived data, also confirm that the file input is inside the form passed to new FormData(form) and is not disabled. Named fields outside that form are not gathered by constructing data from it, and disabled controls are omitted. If you add a second file input or metadata field, ensure the server parser expects those names too.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →The server cannot parse the multipart body
Remove any manually assigned multipart Content-Type header from the fetch options. The browser needs to supply the boundary parameter for the body it generated. Also verify that the endpoint accepts multipart form data rather than expecting a different request format.
Make sure that fetch receives the FormData object itself as the body. Do not convert it to a JSON string, and do not assume that a React route or component automatically acts as a multipart receiver. The URL must reach a server route configured to parse this kind of request.
The UI says success even though the server rejected the request
Check response.ok after awaiting fetch. A fulfilled fetch promise does not by itself mean the server returned a successful status; the example throws when the response is not OK so the error can be shown to the user.
Also popular on Amazon
- Portable and powerful USB-C HUB: BENFEI USB Type-C HUB, with super-soft and knot-free silicone woven design cable, meets most mobile office needs. Compact, lightweight, stylish, and powerful portable USB C Hub equipped with 1 x HDMI port, 1 x 100W charging, and 3 x USB ports. 18-month warranty, 24-hour response, to ensure you feel at ease when using our product.
- Design centered on comfort and reliability: Thanks to BENFEI's end-to-end in-house cable production capability, in-house PCBA and assembly capability, using the industry's most advanced silicone woven design and process, 20cm cable in length, no knots, super-soft, the HUB is easy to use in all scenarios: laptop, tablet, stand etc. Super-soft, 25000+ life cycles, to meet your daily carrying and office needs.
- 100W Charging: Support up to 90W USB C pass-through charging via Type-C port to keep your laptop powered. 10W is reserved for other interface operations. No data and video function on the Type-C port.
- 4K HDMI Display: The HDMI port supports media display at resolutions up to 4K 30Hz, keeping every incredible moment detailed and ultra vivid. Please note that the C port of the Host device needs to support video output.
- Transfer Files in Seconds: Transfer files and from your laptop at speeds up to 10 Gbps with USB A 3.2 port. Extra 2 USB A 2.0 ports are perfectly for your keyboards and mouse.
Keep the distinction between a transfer and a successful upload in mind. The request can reach the server and still be rejected by its validation, authorization, or storage rules. Treat the response status as part of the result, and avoid clearing the selection or announcing completion before the endpoint has indicated success.
Recommended Free Tools
The input has a value but no file is being sent
Read from files or submit the named field with FormData; do not treat the input’s displayed value as a local path. If you build the data from a form, make sure the file input is enabled and named, because disabled fields are excluded.
Finally, check that the submit handler is attached to the form and that it actually sends the constructed data. A file selection by itself does not trigger the example’s POST request; the user submits the form to start that step. If no request is sent, inspect the form handler and its chosen endpoint before changing the file input.
How can I show upload progress?
The example’s “Uploading…” message only indicates that a request is pending; it is not a byte-level percentage. For progress updates during transfer, use an approach with upload-progress events, such as the XMLHttpRequest.upload progress events documented by MDN, rather than assuming that this basic fetch example provides percentage progress.
Fetch makes the basic request concise, but the example above does not expose upload percentage updates. MDN’s documented approach for tracking bytes sent uses an XMLHttpRequest upload progress event. That is a different request implementation, so choose it when byte-level progress is a requirement rather than presenting a pending status as a percentage.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteKeep the same distinctions when adding a progress display: the browser can report transfer progress, while only the server can confirm that it accepted, validated, and stored the file. A completed transfer is not necessarily a successful upload unless the endpoint’s response also indicates success.
Can I use a native picker, drag-and-drop, or a preview?
A native labeled file input is the simplest baseline. Drag-and-drop handlers can read files from event.dataTransfer.files, and an image preview can use file-reading APIs or an object URL. These enhancements change how the user supplies or previews a file; they do not replace the multipart request or the server’s validation and storage work.
Keep a visible, keyboard-usable, labeled file input even if the interface also supports dropping files. The ordinary input remains useful for people who cannot or do not want to drag a file. If an object URL is used for a preview, revoke it when it is no longer needed. A preview is only a way to display a selected file locally; it does not submit the file or establish that the server will accept it.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Should I use a form action or an onSubmit handler?
This tutorial uses an onSubmit event handler because it demonstrates the familiar client-side sequence: prevent the normal navigation, create FormData, send it with fetch, then inspect the response. React’s form reference says that reading form data with onSubmit works in every version of React. React function-valued form actions are another option, but they have different execution semantics; they are not required for this upload pattern.
Choose the approach that fits the application and its React version rather than assuming that every form must use the same mechanism. Whichever client pattern you use, the recipient still needs to accept the submitted data and enforce server-side rules. Check the behavior against the React version and server setup used by your project.
Also popular on Amazon
- 【Read before You Buy】 Note: This adapter is USB 2.0 version and cannot transmit HDM, VGA, or other video signals. Nevertheless, they are fully capable of charging devices,duplicating files, and can be seamlessly integrated with USB-C earphones, wireless network adapters, and SD card adapters.
- 【Easy to Use and Safe】Thanks to modern manufacturing techniques, we've made these adapters sufficiently compact so that they can remain inserted in your device without noticeable protrusion or inconvenience. This means you don't have to constantly plug and unplug them, reducing the likelihood of wear and misalignment, and making them more convenient to carry around.
- 【Reliable Quality】Engineered for enhanced durability, durable aluminum alloy shell material,get excellent wear resistance and heat dissipation,the male USB C and female USB connectors & the male USB and female USB C connectors are designed to be plugged and unplugged up to 20000 times. Provides data transfer, device charging, memory space expansion, and additional computer peripherals.
- 【Think more for you】Do you need to connect a USB-C-enabled device to an odd device that only has USB-A ports? Then these USB-A male to USB-C female adapters are made for you.Simply insert the adapter into the USB-A port on the device, and you can instantly connect your USB-C device to the device that originally didn't have the correct connection port.
- 【Trusted xiwxi Quality and Service】As a responsible brand seller, you will receive xiwxi's 12-month Quality assurance and lifetime friendly customer service, you're not just buying a product,you're investing in peace of mind with all-round quality and exceptional customer service.
What does this example not provide?
The code demonstrates the browser side of a file upload. It does not create the /upload route, parse multipart data, authorize a user, validate file contents, set storage names, store a file, or serve it later. Those decisions depend on the server stack and application. There is no single backend implementation implied by a React-only example.
Likewise, required and accept are user-interface guidance, not trusted enforcement. The server must independently check permissions, allowed types and sizes, content, and storage handling. If the endpoint is absent, uses a different field name, or expects a different request format, the client example cannot complete the upload until those sides are made compatible.
Frequently Asked Questions
Can I upload files without a backend in React?
No. React can collect a browser-selected file and send it, but an endpoint must receive the request and decide what to do with its contents. That endpoint can be part of your own server architecture; it is not supplied by the React component.
Can React upload a file to a local path on the user’s computer?
A web page cannot choose an arbitrary local filesystem path and write a file there through a file input. The picker exposes files the user selects, while saving or storing an upload requires an explicit browser download flow or a server-side destination.
Does the selected file’s MIME type prove it is an image?
No. A client-provided MIME type is not trustworthy evidence of the file’s actual contents. The receiving server should validate the upload independently and enforce its own permitted types and limits.
Can I show a preview before submitting an image?
Yes. A preview can be created from the selected file with file-reading APIs or an object URL. If you use an object URL, revoke it when the preview is no longer needed; the preview does not submit or validate the file.
Why should I not set Content-Type manually for FormData?
The browser needs to add the multipart boundary that separates the request’s parts. Setting the header yourself can leave out or mismatch that boundary and prevent the server from parsing the body. Pass FormData as the request body and leave Content-Type unset.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Does accept validate the file securely?
No. The accept attribute guides the file picker toward intended types; it does not prove the file’s actual contents or make it safe. The receiving server must apply its own type, content, size, and authorization checks.
How do I send every selected file?
Add the multiple attribute to the file input, then use its files collection or call formData.getAll(‘file’) for all values under that field name. The server must be configured for the same multipart field name and may still enforce its own limits.
Does fetch provide an upload percentage in this example?
No. The status message indicates that the request is pending, not how many bytes have transferred. For upload progress, use an approach with progress events, such as XMLHttpRequest.upload, and still check the server response for acceptance.
The Bottom Line
For a basic React file upload, use a labeled named file input, build FormData in the submit handler, and send it with fetch without setting multipart Content-Type manually. Treat the endpoint as a required part of the feature: it must parse the field, check permissions and file rules, and handle storage safely.

