Open In App

File Uploading In ReactJS

Last Updated : 19 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

  1. 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.
  2. 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.

File uploading in React JS is integral to building robust applications. Whether uploading images, videos, or other files , understanding the process is essential. Learn a practical approach to implementing file upload in React with our comprehensive Full Stack Development with React & Node JS course. Covering steps from selecting files using HTML input tags to sending requests to the server with tools like Axios, we empower you to create seamless file upload functionalities in your applications.

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.



Next Article

Similar Reads