DEV Community

Cover image for How to upload images in firebase storage with React.js.
siddharth
siddharth

Posted on • Edited on

How to upload images in firebase storage with React.js.

Hi everyone, I hope you all are safe and doing fine!
Here, we will be uploading an image in firebase storage.
If you're already familiar with JavaScript, React and Firebase, then you'll be able to get moving with this quickly!

Explanation

First create the project using command
npx create-react-app firebase-tutorial

then install the packages that needed for the navigations

yarn add firebase

After installing the project add new folder named as firebase and create new file in folder. The file structure should be as follows
Alt Text

Now its time to create new project on firebase.
Click here.
Alt Text
Click on Add Project

Alt Text

Enter your project name.

Alt Text

Click on create project.

Alt Text
Now add Web app on clicking </> this.

Alt Text
Register your app name.Ex- firebase-image. Click on Register app.

Alt Text

copy this snippet and paste this snippet in firebase.js file.
firebase.js should look like this.

import firebase from 'firebase'

var firebaseConfig = {
  apiKey: "******rBJcUIyThYVrIqg",
  authDomain: "********.firebaseapp.com",
  projectId: "************",
  storageBucket: "**********.appspot.com",
  messagingSenderId: "***************",
  appId: "*****************df5dfbbee0"
};
  firebase.initializeApp(firebaseConfig);
  export default firebase;
Enter fullscreen mode Exit fullscreen mode

Click on storage icon on left sidebar. Now click on Rules. your rules should look like this.
Alt Text
Change the code and publish.Now your rules changes and should look like this.
Alt Text

Now its time to code. Open App.js and follow the below code.

import React, { Component } from 'react'
import './App.css';
import firebase from "./firebase/firebase"

export default class App extends Component {
  constructor(){
    super();
    this.state = {
      image: null,
      progress:0,
      downloadURL: null
    }
  }


  handleChange = (e) =>{
    if(e.target.files[0]){
      this.setState({
      image: e.target.files[0]
    })
  }
    // console.log(e.target.files[0])
}

handleUpload = () =>{
  // console.log(this.state.image);
  let file = this.state.image;
  var storage = firebase.storage();
  var storageRef = storage.ref();
  var uploadTask = storageRef.child('folder/' + file.name).put(file);

  uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
    (snapshot) =>{
      var progress = Math.round((snapshot.bytesTransferred/snapshot.totalBytes))*100
      this.setState({progress})
    },(error) =>{
      throw error
    },() =>{
      // uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) =>{

      uploadTask.snapshot.ref.getDownloadURL().then((url) =>{
        this.setState({
          downloadURL: url
        })
      })
    document.getElementById("file").value = null

   }
 ) 
}


  render() {
    return (
      <div className="App">
        <h4>upload image</h4>
        <label>
          Choose file
        <input type="file" id="file" onChange={this.handleChange} />        
        </label>

        {this.state.progress}
        <button className="button" onClick={this.handleUpload}>Upload</button>
        <img
          className="ref"
          src={this.state.downloadURL || "https://via.placeholder.com/400x300"}
          alt="Uploaded Images"
          height="300"
          width="400"
        />
      </div>
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

CSS

.App {
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}



label{
  align-items: center;
  padding: 12px;
  background: red;
  display: table;
  color: #fff;
  /* margin-left: 700px; */
  /* padding-inline: 40px; */
   }

   .button {
    background-color: #4CAF50; /* Green */
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    margin: 4px 2px;
    cursor: pointer;
  }
.ref{
  margin-top: auto;
}

input[type="file"] {
  display: none;
}

Enter fullscreen mode Exit fullscreen mode

Now run the file using command

npm start

Alt Text

AND DONE
I hope you liked the article!
Thank You!

Top comments (0)