File uploading in React.js


File transmission represents a vital aspect of any online platform, permitting users to effortlessly transfer and disseminate files among each other. With the proliferation of JavaScript libraries and frameworks, file uploading has become significantly easier, with React.js being no exception. In this treatise, we shall delve into the intricacies of file uploading in React.js, exploring the algorithmic approach, various methodologies, and functional illustrations.

Algorithm

At the crux of it, the act of file uploading in React.js entails transmitting a document from the user's machine to the host server. This is achieved by employing a form that comprises an input element designated as "file." Upon the user's selection of a file, it is then dispatched to the server where it undergoes processing before being securely stored.

The procedure of file uploading in React.js can be divided into several phases −

  • The user chooses a file to upload

  • The file is transmitted to the server

  • The server performs the necessary handling and archives the file

  • The user is notified of the successful completion of the upload.

Approaches to File Uploading in React.js

There are two main approaches to file uploading in React.js: using JavaScript and using React-Dropzone.

Method 1: Using JavaScript

The first approach to file uploading in React.js is to use JavaScript. This involves creating a form with an input field of type "file" and then using JavaScript to handle the file upload process.

Example

Here is an example of how to implement file uploading using JavaScript in React.js −

class FileUpload extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         selectedFile: null
      };
   }

   onChangeHandler = event => {
      this.setState({
         selectedFile: event.target.files[0]
      });
   };

   onClickHandler = () => {
      const data = new FormData();
      data.append("file", this.state.selectedFile);
      axios
      .post("/api/upload", data)
      .then(res => {
         console.log(res.statusText);
      })
      .catch(err => {
         console.log(err);
      });
   };

   render

   return (
      <div>
         <input type="file" onChange={this.onChangeHandler} />
         <button onClick={this.onClickHandler}>Upload</button>
      </div>
   );
}

In this illustration, a form that features an input element of type "file" is constructed. Upon the user's selection of a file, the onChangeHandler function is activated, which assigns the selectedFile state to the selected document. The onClickHandler function is then executed once the user clicks the "Upload" button, transmitting the file to the server through the utilization of the axios library.

Method 2: Using React-Dropzone

The second approach to file uploading in React.js is to use the React-Dropzone library. This library provides a simple, easy-to-use solution for file uploading in React.js.

Example

Here is an example of how to implement file uploading using React-Dropzone −

import React, { useState } from "react";
import { useDropzone } from "react-dropzone";

function MyDropzone() {
   const [files, setFiles] = useState([]);
   const { getRootProps, getInputProps } = useDropzone({
      accept: "image/*",
      onDrop: acceptedFiles => {
         setFiles(acceptedFiles.map(file => Object.assign(file, {
            preview: URL.createObjectURL(file)
         })));
      }
   });

   const thumbs = files.map(file => (
      <div key={file.name}>
         <img
         src={file.preview}
         alt={file.name}
         style={{ width: "100px", height: "100px" }}
         />
      </div>
   ));

   return (
      <section className="container">
         <div {...getRootProps({ className: "dropzone" })}>
            <input {...getInputProps()} />
            <p>Drag 'n' drop some files here, or click to select files</p>
         </div>
         <aside>
            {thumbs}
         </aside>
      </section>
   );
}

In this instance, the useDropzone hook from the React-Dropzone library is utilized to manage the file uploading process. The hook offers the getRootProps and getInputProps functions, which are utilized to define the form and input element respectively. Upon the user's deposition of a file into the designated dropzone, the onDrop function is activated, which assigns the files state to the accepted files.

Example 1: Simple file Upload

Here is a simple example of file uploading in React.js.

In this example, a simple file upload form is created using an input field of type "file." When the user selects a file, the onChangeHandler function is triggered, which sets the selectedFile state to the selected file. If a file is selected, the file name and size are displayed, otherwise, a message is displayed indicating that no file has been selected.

import React, { useState } from "react";
const SingleFileUpload = () => {
   const [selectedFile, setSelectedFile] = useState(null);
   const handleFileChange = (e) => {
      setSelectedFile(e.target.files[0]);
   };

   const handleUpload = async () => {
      if (!selectedFile) {
         alert("Please first select a file");
         return;
      }

      const formData = new FormData();
      formData.append("file", selectedFile);

      try {
         // Replace this URL with your server-side endpoint for handling file uploads
         const response = await fetch("https://your-upload-endpoint.com/upload", {
            method: "POST",
            body: formData
         });

         if (response.ok) {
            alert("File upload is  successfully");
         } else {
            alert("Failed to upload the file due to errors");
         }
      } catch (error) {
         console.error("Error while uploading the file:", error);
         alert("Error occurred while uploading the file");
      }
   };

   return (
   <div>
      <h2>Single File Upload</h2>
      <input type="file" onChange={handleFileChange} />
      <button onClick={handleUpload}>Upload</button>
   </div>
   );
};
export default SingleFileUpload;

Output

Example 2: Multiple file Upload

Here is an example of multiple file upload in React.js.

In this example, a form for multiple file upload is created using an input field of type "file" with the multiple attribute. When the user selects files, the onChangeHandler function is triggered, which sets the selectedFiles state to the selected files. If files are selected, the names and sizes of the selected files are displayed in a list, otherwise, a message is displayed indicating that no files have been selected.

import React, { useState } from 'react';
const MultipleFileUpload = () => {
   const [selectedFiles, setSelectedFiles] = useState([]);
   const handleFileChange = (e) => {
      setSelectedFiles([...e.target.files]);
   };
   const handleUpload = async () => {
      if (selectedFiles.length === 0) {
         alert('Please select files first');
         return;
      }
      const formData = new FormData();
      selectedFiles.forEach((file) => {
         formData.append('files', file);
      });
      try {
         // Replace this URL with your server-side endpoint for handling file uploads
         const response = await fetch('https://your-upload-endpoint.com/upload', {
            method: 'POST',
            body: formData,
         });
         if (response.ok) {
            alert('Files uploaded successfully');
         } else {
            alert('Failed to upload the files');
         }
      } catch (error) {
         console.error('Error while uploading the files:', error);
         alert('Error occurred while uploading the files');
      }
   };
   return (
      <div>
         <h2>Multiple File Upload</h2>
         <input type="file" multiple onChange={handleFileChange} />
         <button onClick={handleUpload}>Upload</button>
      </div>
   );
};
export default MultipleFileUpload;

Output

Conclusion

In conclusion, file uploading is a crucial component of any web application, and React.js provides several options for implementing it. Whether you choose to use JavaScript or the React-Dropzone library, the process of file uploading in React.js is relatively straightforward. By following the examples in this article, you should have a good understanding of how to implement file uploading in React.js and be able to create your own file upload form.

Updated on: 17-Apr-2023

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements