File Uploading In ReactJS
Last Updated :
19 Apr, 2025
File uploading in ReactJS is an important functionality for many web applications, especially those that require user interaction, such as submitting forms, uploading images, or handling documents. In this article, we will walk you through the process of implementing file upload functionality in ReactJS.
Prerequisites
Approach to File Upload in React
There are two main steps to handle file uploading in React
- Select a File (user input): The first step is to add the tag to our App component to enable the user to pick a file. This tag should have the type attribute set as “file”. Now, we need an event handler to listen to any changes made to the file. This event handler will be triggered whenever the user selects a new file and will update the state.
- Send a request to the server: After storing the selected file (in the state), we are now required to send it to a server. For this purpose, we can use fetch or Axios. In this code, we use Axios, a promise-based HTTP client for the browser and NodeJS. The file is sent to the service wrapped in a FormData object.
Steps to Implement File Upload in React
Step 1: Initialise Your React Project
Run the following command to create a new React project:
npx create-react app myapp
cd myapp
Step 2: Install Axios
Axios will help us handle HTTP requests. Install it by running:
npm i axios --save
Project Structure

Folder Structure
Dependencies
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",`
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.7.2",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
This example uses axios and input type to accept the valid file input and uploading.
JavaScript
import axios from "axios";
import React, { useState } from "react";
const App = () => {
const [selectedFile, setSelectedFile] = useState(null);
const onFileChange = (event) => {
setSelectedFile(event.target.files[0]);
};
const onFileUpload = () => {
const formData = new FormData();
formData.append(
"myFile",
selectedFile,
selectedFile.name
);
console.log(selectedFile);
axios.post("api/uploadfile", formData);
};
const fileData = () => {
if (selectedFile) {
return (
<div>
<h2>File Details:</h2>
<p>File Name: {selectedFile.name}</p>
<p>File Type: {selectedFile.type}</p>
<p>
Last Modified: {selectedFile.lastModifiedDate.toDateString()}
</p>
</div>
);
} else {
return (
<div>
<br />
<h4>Choose before Pressing the Upload button</h4>
</div>
);
}
};
return (
<div>
<h1>GeeksforGeeks</h1>
<h3>File Upload using React!</h3>
<div>
<input type="file" onChange={onFileChange} />
<button onClick={onFileUpload}>Upload!</button>
</div>
{fileData()}
</div>
);
};
export default App;
Output

File uploading in ReactJS
In this example
- The onFileChange function captures the selected file and updates the selectedFile state.
- The onFileUpload function creates a FormData object, appends the file, and uploads it to the server using axios.post().
- The fileData function shows file details like name, type, and last modified date, or prompts the user to select a file.
Why is File Uploading Important in ReactJS?
File uploading is an essential feature in many modern web applications. Here are some common reasons why it is needed:
- User Interaction: Users may need to upload images, documents, or files as part of their profile setup or other interactions.
- Data Collection: Gathering files as part of forms or surveys.
- Content Management: Allow users to upload multimedia content, like images, audio, or video, for further processing or sharing.
Handling Errors and Validation
When implementing file upload, you must ensure that files meet specific criteria. Here are a few validation checks you can add:
- File Size Validation: Prevent large files from being uploaded by checking the file size
if (this.state.selectedFile.size > 5000000) {
alert("File size exceeds 5MB");
return;
}
- File Type Validation: Allow only specific file types (e.g., images)
if (!this.state.selectedFile.type.startsWith("image/")) {
alert("Please select an image file");
return;
}
- Error Handling: Always handle errors during the upload process and provide feedback to the user
axios.post("api/uploadfile", formData)
.then(response => {
console.log("File uploaded successfully:", response.data);
})
.catch(error => {
console.error("Error uploading file:", error);
alert("File upload failed. Please try again.");
});
Conclusion
React class component demonstrates how to handle file uploads by allowing users to select a file, upload it to the server using Axios, and display file details once uploaded. By using FormData and axios.post(), the process becomes seamless, making it a valuable feature for applications requiring file handling.
Similar Reads
How to upload files in firebase storage using ReactJS ?
Firebase Storage is a powerful cloud storage solution provided by Google's Firebase platform. It allows developers to store and retrieve user-generated content, such as images, videos, and other files, in a secure and scalable manner. In this article, we will explore how to upload files to Firebase
2 min read
ReactJS | Using Babel
Now we know that what Babel is, we will focus on how to install it on your machine using node. Babel can be installed easily after following these simple steps. Requirements : A code editor like atom, sublime text or Visual studio code.Node should be installed on the machine with npm too. We will in
2 min read
How to create a upload file button in ReactJS?
File upload button is a commen feature in React Apps used to take the file input from user and process it. To perform this we can simple use input type file and trigger the input event with the help of upload button. ApproachTo create a upload file button in React we will be using the input type fil
3 min read
How to Upload Files in JavaScript?
We upload files using JavaScript, for this we have to capture form elements, gather information from FormData for easier file uploads, intercept submission events, and utilize Fetch API for asynchronous server requests, for enhanced user experience and efficient data handling. ApproachProject Setup:
1 min read
How to Upload Image and Preview it Using ReactJS?
In React upload and preview images improve the user experience of the application, It's typical for online apps to provide image upload capability that enables users to choose and upload photographs. We simply upload a photo from our local device to our React Project and preview it using a static me
2 min read
ReactJS UI Ant Design Upload Component
The Ant Design Upload Component is used to upload files such as images, documents, or any other type of file. It provides various features, such as drag-and-drop support, progress tracking, and customizable upload lists. Syntax: <Upload action="/https/www.geeksforgeeks.org/upload" listType="picture"> <Button icon={
4 min read
Bill/Invoice Generator using React
Bill/Invoice Generator website using React helps users easily make, customize, and print invoices and can add or delete items. It uses React's building blocks to make the design easy to update and reuse. The user also has a feature of downloading the pdf version of the generated bill Preview of fina
5 min read
React Suite Uploader Component
React Suite is a popular front-end library with a set of React components that are designed for the middle platform and back-end products. Uploader component allows the user to upload files from the system. We can use the following approach in ReactJS to use the React Suite Uploader Component. Uploa
3 min read
Working with Forms in React
React Forms are an important part of most web applications. They allow users to input data and interact with the application. Forms are used to collect the data from the user and process it as required whether in login-signup forms or surveys etc. Prerequisites:NPM & Node.jsReact JSHTML FormReac
3 min read
Image Compressor using ReactJS
This article focuses on crafting an Interactive Feature-based Image Compressor utilizing the ReactJS library. Users can upload image files and adjust compression quality via a slider. Upon setting the compression quality and initiating compression, users can download the compressed image locally. Ad
7 min read