Why Doesnt Firebase Just Let Me Upload My Files
Firebase is a mobile and web application development platform created by Google that provides products and solutions that yous tin can rely on for you lot app evolution needs, including Cloud Firestore, Cloud Functions, Authentication, Hosting, Realtime Database, Deject Storage, and more.
Cloud storage service is designed for developers to easily store and serve user-generated content like photos and videos, which are stored in Google Cloud Storage buckets. In add-on, Firebase Cloud Storage integrates with other Firebase services similar Firebase Authentication and so that users tin can organize uploaded files and utilize access controls if needed.
In this article, we'll learn how to upload a file to Firebase Cloud Storage and access the URL of the uploaded file using Firebase v9.x,the latest version at the time of writing. To follow forth with this commodity, y'all'll need:
- npm and Node.js installed
- Knowledge of React and React Hooks
- A Google account to access Firebase Console
Permit'due south become started!
Table of contents
- Create a project on Firebase
- Create a new React app
- Create a Cloud Storage bucket
- Programmatically upload and read files
- Conclusion
Create a projection on Firebase
Go to Firebase Console at https://console.firebase.google.com/. You'll see the homepage:
Click on the Create a Project button. Type in the name of your projection. I'll proper noun mine React-Firebase-storage
. Accept the Firebase terms and click Proceed:
If you'd similar to use Google Analytics in your project, and then leave the Enable Google Analytics toggle on. I don't need it for this demo, so I'm going to plow it off. Click on Create projection and await for the project to exist created:
Click on Continue to continue to the console:
In the side by side interface, nosotros'll select the platform we desire to use to build the application we just created. In this case, it's going to be on web, and so we cull web:
Next, we enter a name to register the app. Since I'm not going to host the app on Firebase, I'll skip that and click on Register app:
Next, we'll initialize a new React app and add Firebase to the project with the credentials provided:
Create a new React app
Create a new React app with the control below:
npx create-react-app app-proper name
Next, install Firebase equally follows:
npm install firebase
Create a new file in the src
folder called firebase.js
. Re-create the configuration lawmaking from when we created a Firebase project and paste it in the firebase.js
file.
Initialize the Firebase app using the config object containing the credentials and export it. You'll also export a reference to the storage service, which is used to create references in your storage:
// Import the functions yous need from the SDKs you need import { initializeApp } from "firebase/app"; import { getStorage } from "firebase/storage"; // TODO: Add SDKs for Firebase products that you desire to apply // https://firebase.google.com/docs/web/setup#bachelor-libraries // Your web app'southward Firebase configuration const firebaseConfig = { apiKey: "************************************", authDomain: "react-firebase-storage-ae047.firebaseapp.com", projectId: "react-firebase-storage-ae047", storageBucket: "react-firebase-storage-ae047.appspot.com", messagingSenderId: "1071019670975", appId: "1:1071019670975:web:74cc537cd214fb923a750a" }; // Initialize Firebase export const app = initializeApp(firebaseConfig); export const storage = getStorage(app);
In App.js
, let's create a form for uploading files and a button for submitting:
import './App.css'; function App() { render ( <div className="App"> <form className='form'> <input type='file' /> <button blazon='submit'>Upload</button> </course> </div> ); } export default App;
Create a Deject Storage bucket
To utilise any of the Firebase services in your app, you have to set them up for that particular project in Firebase Panel. Therefore, Firebase knows that this app is using said product.
After copying the config code in Firebase console, click on Get to console. Nosotros'll be shown an interface listing all the products we could use. On the left menu bar, click Storage:
Click on Get Started:
For the purpose of this demo, we'll choose test style. But for production applications, y'all should choose production mode to limit who tin read and write to the storage. Click Adjacent:
Select Cloud Storage location and click Done:
Now, we can programmatically upload files to the Cloud Storage bucket and also read those files:
Programmatically upload and read files
With that, everything is set upward for us to write the code for uploading files. In App.js
, we'll start by importing the storage we exported from the Firebase config file, the methods we'll utilize from firebase/storage
, and the React useState
Claw:
import { useState } from "react"; import { storage } from './firebase'; import { ref, getDownloadURL, uploadBytesResumable } from "firebase/storage";
Let's write a function that will run when a user hits the submit push button:
const [imgUrl, setImgUrl] = useState(naught); const [progresspercent, setProgresspercent] = useState(0); const handleSubmit = (e) => { eastward.preventDefault() const file = e.target[0]?.files[0] if (!file) return; const storageRef = ref(storage, `files/${file.name}`); const uploadTask = uploadBytesResumable(storageRef, file); uploadTask.on("state_changed", (snapshot) => { const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100); setProgresspercent(progress); }, (error) => { warning(error); }, () => { getDownloadURL(uploadTask.snapshot.ref).and then((downloadURL) => { setImgUrl(downloadURL) }); } ); }
Let's suspension down what is occurring in the handleSubmit
function. Nosotros initialized two states for the image URL later on we read the uploaded file and the progress value as the image is being uploaded.
const file = e.target[0]?.files[0]
created a variable and saved the supplied file to it.
Adjacent, nosotros created a reference to the file we want to operate on past calling the ref()
on the instance of the storage service we already created in the config file. Equally the 2d parameter, nosotros passed in a path we want the ref to indicate to, which is optional.
Once the reference has been created, we can upload a file by calling the uploadBytesResumable()
. Information technology takes the reference we created earlier and then the file to exist uploaded to cloud storage. Note that uploadBytes()
does exactly the same thing, then either one can exist used.
However, with uploadBytesResumable()
, the upload can exist paused and resumed, and information technology exposes progress updates. We use it here considering we desire to display the progress of the upload as it's ongoing. If you don't want that functionality, feel free to utilizeuploadBytes()
.
Adjacent, we telephone call the on()
method on the hope returned from calling uploadBytesResumable()
to heed for state changes, errors, and successful uploads. These 3 callback functions are run at different stages of the file upload. The first runs during the upload to detect state change events like progress, pause, and resume, while the next one is triggered when in that location is an unsuccessful upload. Finally, the concluding is run when the upload completes successfully.
On successful upload, we call the getDownloadURL()
to go the download URL of the file to brandish on the app. We then update land with the new image URL downloaded.
The total code for displaying the prototype and progress bar is shown below:
import './App.css'; import { useState } from "react"; import { storage } from './firebase'; import { ref, getDownloadURL, uploadBytesResumable } from "firebase/storage"; function App() { const [imgUrl, setImgUrl] = useState(null); const [progresspercent, setProgresspercent] = useState(0); const handleSubmit = (east) => { due east.preventDefault() const file = east.target[0]?.files[0] if (!file) return; const storageRef = ref(storage, `files/${file.name}`); const uploadTask = uploadBytesResumable(storageRef, file); uploadTask.on("state_changed", (snapshot) => { const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100); setProgresspercent(progress); }, (fault) => { alarm(error); }, () => { getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => { setImgUrl(downloadURL) }); } ); } return ( <div className="App"> <class onSubmit={handleSubmit} className='form'> <input type='file' /> <push button type='submit'>Upload</push button> </class> { !imgUrl && <div className='outerbar'> <div className='innerbar' style={{ width: `${progresspercent}%` }}>{progresspercent}%</div> </div> } { imgUrl && <img src={imgUrl} alt='uploaded file' height={200} /> } </div> ); } export default App;
Conclusion
Firebase Cloud storage is very like shooting fish in a barrel to use for storing unlike media types. In addition, information technology automatically scales, and so y'all don't have to worry about moving to another provider when your data gets too big.
Thanks for reading. I hope you constitute this tutorial helpful in some manner. Feel free to ask any questions in the comments below. Happy coding!
LogRocket: Total visibility into your web apps
LogRocket is a frontend application monitoring solution that lets you replay problems equally if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to chop-chop sympathise what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
In add-on to logging Redux actions and state, LogRocket records panel logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. Information technology also instruments the DOM to record the HTML and CSS on the folio, recreating pixel-perfect videos of even the virtually circuitous unmarried-page apps.
Try information technology for free.
Source: https://blog.logrocket.com/firebase-cloud-storage-firebase-v9-react/
0 Response to "Why Doesnt Firebase Just Let Me Upload My Files"
Post a Comment