In this blog, I will focus on using Firebase to store images uploaded by clients. I won't delve into setting up MongoDB or backend API creation, assuming you're already familiar with those. Instead, I'll cover how to upload images to Firebase and then store their Firebase URLs in MongoDB.



1.Set up Firebase

  • Create a Firebase Project:
  • Go to the Firebase Console (console.firebase.google.com).
  • Click on "Add project" and follow the prompts to create a new Firebase project.

Set Up Firebase Authentication (Optional):

  • this is step is only google sign/authentication feature
  • If needed, set up Firebase Authentication for securing your app's features:
  • Go to "Authentication" in the Firebase Console.
  • Click "Get started" and follow the steps to enable authentication methods like email/password, Google sign-in, etc.


Get Firebase Configuration:

  • After setting up your project, retrieve your Firebase configuration:
  • In the Firebase Console, go to your project settings (gear icon).
  • Under the "General" tab, scroll down to "Your apps" section.
  • Click on the Firebase SDK snippet (</>) for web apps.
  • Copy the configuration object (apiKey, authDomain, projectId, storageBucket, messagingSenderId, appId).

2. Integrate with React.js

install firebase using below command in reactjs application

npm install firebase


in ReactJs project create a file any name u want and then add the below code

Create a Firebase configuration file (firebaseConfig.js) and add your Firebase project configuration:


// firebaseConfig.js
import firebase from 'firebase/app';
import 'firebase/firestore'; // for Firestore if needed
import 'firebase/storage';
const firebaseConfig = {
 apiKey: "YOUR_API_KEY",
 authDomain: "YOUR_AUTH_DOMAIN",
 projectId: "YOUR_PROJECT_ID",
 storageBucket: "YOUR_STORAGE_BUCKET",
 messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
 appId: "YOUR_APP_ID"
};
firebase.initializeApp(firebaseConfig);
const storage = firebase.storage();
export { storage, firebase as default };


3 Create Image Upload and Data Posting Component in React

// ImageUpload.js
import React, { useState } from 'react';
import { storage } from './firebaseConfig'; // adjust path as needed
const ImageUpload = () => {
 const initialFormData = {
  image: null,
  title: '',
  description: '',
  imageUrl: ''
 };
 const [formData, setFormData] = useState(initialFormData);
const handleChange = (e) => {
  const { name, value, files } = e.target;
  if (name === 'image') {
   setFormData({
    ...formData,
    image: files[0]
   });
  } else {
   setFormData({
    ...formData,
    [name]: value
   });
  }
 };
 const handleImageUpload = () => {
  if (formData.image) {
   const uploadTask = storage.ref(`images/${formData.image.name}`).put(formData.image);
   uploadTask.on(
    'state_changed',
    (snapshot) => {
    // progress function if needed
    },
    (error) => {
     console.error('Error uploading image to Firebase:', error);
    },
    () => {
     storage
      .ref('images')
      .child(formData.image.name)
      .getDownloadURL()
      .then(url => {
       setFormData({
        ...formData,
        imageUrl: url
       });
      })
      .catch(error => {
       console.error('Error getting download URL:', error);
      });
    }
   );
  } else {
   console.error('Please select an image to upload.');
  }
 };
 const handleSubmit = (e) => {
  e.preventDefault();
  if (formData.imageUrl && formData.title && formData.description) {
   const data = {
    imageUrl: formData.imageUrl,
    title: formData.title,
    description: formData.description
   };
   // Handle submitting data to API or further processing
   console.log('Submitting data:', data);
   // Optionally reset form fields and state
   setFormData(initialFormData);
  } else {
   console.error('Please fill out all fields and upload an image.');
  }
 };
 return (
  <div>
   <form onSubmit={handleSubmit}>
    <input type="file" name="image" onChange={handleChange} />
    <input type="text" name="title" placeholder="Title" value={formData.title} onChange={handleChange} />
    <textarea name="description" placeholder="Description" value={formData.description} onChange={handleChange} />
    <button type="button" onClick={handleImageUpload}>Upload Image</button>
    <button type="submit">Submit</button>
   </form>
  </div>
 );
};
export default ImageUpload;


this will send ur image to firebase and set the url in mongodb database or any database u are using


Steps to Verify Image Upload in Firebase Storage

  1. Navigate to Firebase Console:
  • Go to https://console.firebase.google.com and select your project.
  1. Access Firebase Storage:
  • In the left-hand sidebar, click on Storage.
  1. Find the Uploaded Image:
  • In the file browser, navigate to the folder where your image was uploaded (e.g., images).
  1. Verify the Image:
  • Locate the image by its name.
  • Click on the image to open its details.
  • Check the file details, including its download URL.

These steps will help you quickly verify if your image has been uploaded to Firebase Storage.