How to Upload Image in Firebase Storage
Google's Firebase is a platform for building mobile and online applications. It offers products and services, such as Cloud Firestore, Cloud Functions, Authentication, Hosting, Realtime Database, Cloud Storage, and more, that you can rely on for your app development needs.
Developers may simply store and display user-generated material like photographs and movies that are kept in Google Cloud Storage buckets thanks to the cloud storage service. Users may organise uploaded files and implement access controls as necessary thanks to Firebase Cloud Storage's integration with other Firebase services like Firebase Authentication.
Create a new file in the src
folder called firebase.js
. Copy the configuration code from when we created a Firebase project and paste it in the firebase.js
file.
Export the configuration object with the credentials and use them to launch the Firebase application. A reference that is used to create references in your storage is also exported to the storage service:
import { initializeApp } from 'firebase/app'; import { getFirestore, collection, getDocs } from 'firebase/firestore'; import { getStorage } from "firebase/storage"; const firebaseConfig = { apiKey: "***************************************", authDomain: "playerofcode368712.firebaseapp.com", projectId: "playerofcode-368712", storageBucket: "playerofcode-368712.appspot.com", messagingSenderId: "937825775089", appId: "1:937825775089:web:19f0d7a0fa9bae1910e850" }; const app = initializeApp(firebaseConfig); const db = getFirestore(app); const storage = getStorage(app); const init = { db, storage, app } export default init;
import React,{useState} from 'react' import { ref, uploadBytes, uploadBytesResumable, getDownloadURL } from "firebase/storage"; import init from './firebase'; const ImageUpload = () => { const [imgUrl, setImgUrl] = useState(null); const [progresspercent, setProgresspercent] = useState(0); const imgHandler = (e) =>{ e.preventDefault(); const file=e.target[0].files[0]; const storageRef = ref(init.storage, `${file.name}`); const uploadTask= uploadBytesResumable(storageRef,file); uploadTask.on('state_changed', (snapshot) => { const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100); setProgresspercent(progress); }, (err) => { console.log(err); }, () => { getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => { setImgUrl(downloadURL); }); } ); } return ( <div> <form onSubmit={imgHandler}> <input type="file" /> <button type="submit" >Upload</button> </form> {!imgUrl && <h5>{progresspercent}% uploading</h5> } { imgUrl && <img src={imgUrl} alt='uploaded file' height={200} /> } </div> ) } export default ImageUpload