How to upload images in React Js

In this tutorial, you will learn How to upload images to a folder in React.js, you’ll need to use a combination of React for the frontend and a backend server to handle the file upload and storage.

So, here you will get the frontend react js code to accept the selected images from an HTML form and process them to the backend server using Axios

Steps to upload images in React Js

Now, Let’s start coding to upload a single image at a time using React JS with the given simple steps –

Before getting started you must create a new React app. If you have already done it then skip this step

npx create-react-app myapp

Now, You need to install the Axios  dependencies using the following command

npm install axios

Create a Folder Structure

First of All, create the following folder structure –

myapp/
 |__src/
 |   |__components/
 |   |     |__ImageUpload.js
     |__App.js

 

Create an Image Upload Component

The code defines a React functional component (ImageUpload) that allows users to select an image file, and handles the file selection using state (file), and, upon clicking the “Upload” button, sends the file to a specified backend endpoint using Axios, displaying success or error messages based on the server response.

File name – ImageUpload.js

import React, { useState } from 'react';
import axios from 'axios';


const ImageUpload = () => {
  const [file, setFile] = useState(null);
  const [msg, setMsg] = useState('');

  const handleFileChange = (e) => {
    setFile(e.target.files[0]);
  };

  const handleUpload = async () => {
    try {
      const formData = new FormData();
      formData.append('image', file);

      // Replace 'http://localhost:3001/upload' with your backend API endpoint
      const endpoint = 'http://localhost:3001/upload';
      const response = await axios.post(endpoint, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      
      if(response.data.success){
        setMsg('File Uploaded successfully');
      } else {
        setMsg(response.data.Errormsg)
      }

    } catch (error) {
      console.error('Error uploading file:', error);
    }
  };

  return (
    <div>
     <p>{msg}</p>
       <input type="file" onChange={handleFileChange} />
     
        <button onClick={handleUpload}>
          Upload
        </button>
     
    </div>
  );
};

export default ImageUpload;

Explanation –

  • State Initialization: Two state variables (file and msg) are initialized to manage the selected file and display messages during file upload.
  • File Change Handler: The handleFileChange function updates the file state when a user selects a file.
  • File Upload Function: The handleUpload function, using Axios, sends the selected file to a specified backend endpoint.
  • Form Data Preparation: A FormData object is created and the selected file is appended to it for the HTTP request.
  • Axios Post Request: An asynchronous POST request is made to the backend with the prepared form data and necessary headers.
  • Handling Server Response: The response is checked, and the message state is updated based on the success or error status.
  • Rendering: The component renders file input, a button to trigger upload, and a paragraph for displaying upload status messages.

Render Image Upload Component

To render the image upload component, import it into the App component

File Name – App.js

import ImageUpload from "./components/ImageUpload";
function App() {
  return (
   <ImageUpload />
  );
}

export default App;

Run the React App

Now, Start your development server using the following command

npm start

Then you get the following react app URL to run on the local

http://localhost:3000/

 

Suggestion

I hope you completely understand uploading images to the folder using React JS.  Now, You can implement it with the backend rest API.

The given React Image upload script handles to selection of the image from the locale storage and processes to the file type input. To upload to your project folder and the database, You can use any Rest API.

You can also use the following  rest Api –

Image Upload Rest Api using PHP & MySQL