How to Upload Files to Firebase Storage Using React.js

Firebase Storage provides a simple way to store user-generated data such as images, videos, and audio files. It integrates with Firebase authentication, so you can control who has access to the files.

You can host a large amount of content using Firebase because it automatically scales to fit your needs. It’s simple to use with third-party frameworks like the React JavaScript library

Project setting

To upload files to Firebase storage, you need to create a web form that allows users to select files from the file system.

Start by creating a React app using create-react-app. Run this command to create a React project called firebase-upload:

npx create-react-app firebase-upload

To keep it simple, you just need an input button that accepts the file and an upload button. Replace the content of App.js with the following code.

import {useState} from "react"

function App() {
const [file, setFile] = useState("");

// Handles input change event and updates state
function handleChange(event) {
setFile(event.target.files[0]);
}

return (
<div>
<input type="file" accept="image/*" onChange={handleChange}/>
<button>Upload to Firebase</button>
</div>
);
}

export default App;

MAKE A VIDEO OF THE DAY

In the above code, input card of Accept property is set to only allow images. The handleChange() function that handles input changes and updates the state to store the selected file.

Firebase Setup

Before you can upload files to Firebase storage, you need to create a Firebase project.

Create a Firebase project

Follow the instructions below to create a Firebase project:

  1. Go to Firebase console page and click More projects or Create a project (if you are creating a project for the first time).
  2. Name your project and click There’s more.

  3. Uncheck Google Analytics because you don’t need it for this project and click Create project.

  4. Click There’s more when the project is ready.
  5. Click web icon on the project dashboard to register a web application.

  6. Give your app a nickname and click Registration.
  7. Copy the provided configuration object. You will need it to connect your app to Firebase.


Create a cloud storage group

Firebase stores files in a cloud storage bucket. Follow these steps to create it:

  1. On the project dashboard, click Warehouse on the left navigation panel.

  2. Click Begin and choose test mode.

  3. Select the default storage location and click Accomplished.

You’re now ready to start uploading files to Firebase storage.

Adding Firebase to React

In your terminal, navigate to your React project folder. Run the following command to install the Firebase SDK:

npm install firebase

Create a new file, firebaseConfig.jsand launch Firebase.

import { initializeApp } from "firebase/app";
import { getStorage } from "firebase/storage";


const app = initializeApp ({
apiKey: <apiKey>,
authDomain: <authDomain>,
projectId: <projectId>,
storageBucket: <storageBucket>,
messagingSenderId: <messagingSenderId>,
appId: <appId>,
measurementId: <measurementId>,
});


const storage = getStorage(app);
export default storage;


Use the configuration object you got after creating the Firebase project to launch the Firebase app.

The last line exports the Firebase storage reference so you can access that instance from the rest of your app.

Create a handler function to upload images to Firebase

Clicking the upload button will trigger the function responsible for uploading files to Firebase storage. Let’s create that function.

In App.jsadd function handling. In this function check if the file is empty because the user can click the upload button before selecting the file. If the file doesn’t exist, issue a warning asking the user to upload the file first.

function handleUpload() {
if (!file) {
alert("Please choose a file first!")
}
}

If the file exists, create a memory reference. The memory reference acts as a pointer to the file in the Cloud that you want to operate on.

Start by importing the hosting you created in firebaseConfig.js file.

import storage from "./firebaseConfig.js"

Import ref from Firebase hosted instance and pass in storage service and file path as arguments.

import {ref} from "firebase/storage"

function handleUpload() {
if (!file) {
alert("Please choose a file first!")
}

const storageRef = ref(storage, `/files/${file.name}`)
}

Next, create an upload task by passing the Firebase storage instance in uploadBytesResumable() Constan. There are several methods you can use, but this particular method allows you to pause and resume uploads. It also shows progress updates.

The uploadBytesResumable() function accepts memory and file references for upload.

import {
ref,
uploadBytesResumable
} from "firebase/storage";

function handleUpload() {
if (!file) {
alert("Please choose a file first!")
}

const storageRef = ref(storage, `/files/${file.name}`)
const uploadTask = uploadBytesResumable(storageRef, file);
}

To monitor progress and handle errors as files upload, listen for status changes, errors, and completions.

import {
ref,
uploadBytesResumable,
getDownloadURL
} from "firebase/storage";

function handleUpload() {
if (!file) {
alert("Please choose a file first!")
}

const storageRef = ref(storage,`/files/${file.name}`)
const uploadTask = uploadBytesResumable(storageRef, file);

uploadTask.on(
"state_changed",
(snapshot) => {
const percent = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);


setPercent(percent);
},
(err) => console.log(err),
() => {
getDownloadURL(uploadTask.snapshot.ref).then((url) => {
console.log(url);
});
}
);
}


This, state_changed event has three callback functions. In the first function you are tracking the upload progress and upload progress status. In the second callback function, handle the error if the upload failed.

The final function will run after the upload is complete and get the download URL, then display it on the console. In a real life application, you can save it to a database.

You can display the progress status of the upload using the percentage status. Also add one in one click event on upload button to fire handling Constan.

import {  useState } from "react";

function App() {
const [percent, setPercent] = useState(0);

return (
<div>
<input type="file" onChange={handleChange} accept="" />
<button onClick={handleUpload}>Upload to Firebase</button>
<p>{percent} "% done"</p>
</div>
)
}


Here is the complete code for App.js:

import { useState } from "react";
import { storage } from "./firebaseConfig";
import { ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";

function App() {
const [file, setFile] = useState("");


const [percent, setPercent] = useState(0);


function handleChange(event) {
setFile(event.target.files[0]);
}

const handleUpload = () => {
if (!file) {
alert("Please upload an image first!");
}

const storageRef = ref(storage, `/files/${file.name}`);


const uploadTask = uploadBytesResumable(storageRef, file);

uploadTask.on(
"state_changed",
(snapshot) => {
const percent = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);


setPercent(percent);
},
(err) => console.log(err),
() => {
getDownloadURL(uploadTask.snapshot.ref).then((url) => {
console.log(url);
});
}
);
};

return (
<div>
<input type="file" onChange={handleChange} accept="/image/*" />
<button onClick={handleUpload}>Upload to Firebase</button>
<p>{percent} "% done"</p>
</div>
);
}

export default App;


Do more with Firebase storage

File uploading is one of the most basic features of Firebase storage. However, there are other things that Firebase storage allows you to do. You can access, display, organize, and delete your files.

In a more complex application, you might want to authenticate users to give them permission to interact only with their files.


code with security key

User Authentication with Firebase & React

Continue reading


About the author

https://www.makeuseof.com/upload-files-to-firebase-using-reactjs/ How to Upload Files to Firebase Storage Using React.js

Sarah Ridley

USTimesPost.com is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – admin@ustimespost.com. The content will be deleted within 24 hours.

Related Articles

Back to top button