It’s important to know that the task of enabling file uploads within a React application is fundamental for building different web applications. Such applications include image galleries and file management systems. In this Answer, our prime focus will be on the front-end aspect of the problem, talking through the creation of a basic React application that implements the feature of uploading files using a form.
Here’s a visual of what to expect when we implement using a simple form for uploading files in React.
Here are the key steps to complete the task of implementing the file upload feature in React:
If we don’t have a React app already set up on our systems, we can create one by executing the following commands, one after the other:
npx create-react-app <folder-name>
cd <folder-name
Note: In the place of the
<folder-name>
tag/placeholder, we can write a directory name of our choice.
Inside the /src
folder of our React project, we’ll create a new component for the file uploading feature. This component contains the following code:
import React, { useState } from 'react';import './fileupload.css';function FileUpload() {// Initializing selectedFile, setSelectedFile variables to display the details of the uploaded file in the console windowconst [selectedFile, setSelectedFile] = useState(null);// Initializing uploadSuccess, setUploadSuccess variables to display a message verifying that the upload is successfulconst [uploadSuccess, setUploadSuccess] = useState(false);// Initializing uploadFailed, setUploadFailed variables to display a message in case the file uploading operation is unsuccessfulconst [uploadFailed, setUploadFailed] = useState(false);// Initializing fileDetails, setFileDetails variables to store file informationconst [fileDetails, setFileDetails] = useState(null);// Initializing uploadProgress, setUploadProgress variables to track the upload progresslet [uploadProgress, setUploadProgress] = useState(0);// Initalizing description, setDescription variables for adding descriptionconst [description, setDescription] = useState('');//Initializing uploadDateTime, setUploadDateTime variables for file upload date and timeconst [uploadDateTime, setUploadDateTime] = useState('');// Function to handle file input changeconst handleFileChange = (event) => {setSelectedFile(event.target.files[0]);setFileDetails(null); //clears the file details from the webpage};// Function to handle form submissionconst handleSubmit = (event) => {//this function prevents default submission behaviorevent.preventDefault();if (selectedFile) {// If the upload date and time is not entered, display an error messageif (!uploadDateTime) {setUploadFailed(true); //initializing the upload failed variable to truesetUploadSuccess(false); //initializing the upload success variable to falsesetFileDetails(null);} else {setUploadSuccess(false); //seting the upload success variable to falsesetUploadFailed(false); //setting the upload failed variable to falsesetUploadProgress(0); //setting upload progress to zero// Simulate upload progress using a timeoutconst uploadInterval = setInterval(() => {if (uploadProgress < 100) { //checking if upload progress is less than 100uploadProgress = uploadProgress + 10;setUploadProgress(uploadProgress);} else { //when the upload process reaches 100%//the progress simulation interval is stoppedclearInterval(uploadInterval);// Set upload success variable to truesetUploadSuccess(true);//calculating the filesize in KBs, and setting its details (e.g., name, type, and filesize)const fileSizeInKB = Math.round(selectedFile.size / 1024);setFileDetails({name: selectedFile.name,type: selectedFile.type,size: fileSizeInKB,});console.log('Uploaded File:', selectedFile);}}, 800); //Simulating upload progress every 0.8 seconds}} else {setUploadFailed(true);setUploadSuccess(false);setFileDetails(null);}};// Extra function to refresh the page after uploading the fileconst refreshPage = () => {setSelectedFile(null); // Clear the selected filesetFileDetails(null);setUploadSuccess(false);setUploadFailed(false);setUploadProgress(0); //reset the upload progress to zerowindow.location.reload();};// Render method within the return statement that triggers handleSubmit and handleFileChange// Extra features implemented including printing the details of the file uploaded as well as a message showing that the upload was successful;// In the case of no file being uploaded, a refresh button appears to try uploading files againreturn (<div><h2>Uploading files using a form in React</h2><form onSubmit={handleSubmit}><input className="title" id="fileInput" type="file" onChange={handleFileChange} />{/*adding a description field for adding description of the file to be uploaded*/}<inputclassName="description-input"type="text"placeholder="Enter description"value={description}onChange={(e) => setDescription(e.target.value)}/>{/* Adding input field for upload date and time */}<font size= "3"> Upload date: </font><inputtype="datetime-local"value={uploadDateTime}onChange={(e) => setUploadDateTime(e.target.value)}/><button type="submit">Upload</button></form><div>{uploadProgress > 0 && uploadProgress < 100 && (<div><b className="right-shift">Uploading...</b><progress value={uploadProgress} max="100">{uploadProgress}%</progress></div>)}{uploadSuccess && (<div><b className="right-shift">Uploaded successfully!</b><p>Details of file uploaded:</p><p>Name: {fileDetails.name}</p><p>Type: {fileDetails.type}</p><p>Description: {description}</p><p>Upload date and time: {uploadDateTime}</p><button onClick={refreshPage}>Remove File</button></div>)}{uploadFailed && <b className="right-shift">Upload failed. Please try again!</b>}{uploadFailed && <button onClick={refreshPage}>Refresh</button>}</div></div>);}export default FileUpload;
In the code above, event handlers handleFileChange
and handleSubmit
are responsible for selecting a file and uploading it on the web page. Also, various state variables (e.g., uploadSuccess
, uploadFailure
, etc.) are updated to provide feedback to the user consisting of the render
method within the return
statement is called when the React app starts.
Note: To read more about event handlers in React, check out this answer.
An interesting thing to note is that between the <form>
tags, we’ve added two additional input fields that take the date and time of the file being uploaded, as well as its description. This gives the file upload form a more interactive feel when the user uploads a file for the first time.
Next, we’ll import the component made in the step above in the App.js
file (present in the /src
directory as well) by writing the following code:
import React from 'react';import './App.css';import FileUpload from './FileUpload';function App() {//adding the contents of the FileUpload form inside <div> classes for better code organizationreturn (<div className="App"><header className="App-header"><FileUpload /></header></div>);}export default App;
Note: We can replace
./FileUpload
with any file name of our choice for our file upload component. We need to make sure that the file name in which we made the component is written properly in theimport
statement of theApp.js
file.
After incorporating the steps outlined above, we’ll finally start the React app with the npm start
command.
In this section, we can see what the React app with the file uploading feature will look like after incorporating all of the steps above. Feel free to add your own inputs to see the results!
The steps to fill the upload form can be seen in the slides below in which we start off with uploading the file in the first step, followed by adding a description for the file to be uploaded, and then setting the upload date of the file.
The fields in the form can be filled in any order we prefer, making sure that the date of upload is entered properly to avoid any possible errors as shown in the following slides. After filling out the form, we can verify that the files have been successfully uploaded as illustrated in the slides shown below.
Here, we right click the “Inspect” option to be able to navigate to the console
section to see that the files have been successfully uploaded on the web page.
To summarize, the solution written above represents a simple React component that provides a basic file upload form. When we select a file and submit the form, it logs the selected file’s information to the console, verifying that frontend of the file upload process was successful. In a real-world application, we’re free to extend this code to handle file uploads to a server.
Free Resources