React Native Uploading Files to Google Cloud

Firebase is a mobile and web awarding evolution platform created past Google that provides products and solutions that yous tin rely on for you app development needs, including Cloud Firestore, Cloud Functions, Authentication, Hosting, Realtime Database, Cloud 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 addition, Firebase Cloud Storage integrates with other Firebase services like Firebase Authentication so that users tin organize uploaded files and apply access controls if needed.

In this article, we'll learn how to upload a file to Firebase Deject Storage and access the URL of the uploaded file using Firebase v9.x,the latest version at the fourth dimension of writing. To follow along with this article, you lot'll demand:

  • npm and Node.js installed
  • Cognition of React and React Hooks
  • A Google account to access Firebase Console

Let's 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 project on Firebase

Go to Firebase Panel at https://console.firebase.google.com/. You'll see the homepage:

Firebase Console Homepage

Click on the Create a Projection button. Type in the proper noun of your projection. I'll name mine React-Firebase-storage. Accept the Firebase terms and click Continue:

Create Project React Firebase Storage

If y'all'd like to use Google Analytics in your project, then leave the Enable Google Analytics toggle on. I don't need information technology for this demo, so I'm going to turn it off. Click on Create project and wait for the project to be created:

Google Analytics Firebase Project

Click on Proceed to go along to the console:

Continue Console React Firebase Storage

In the next interface, we'll select the platform we desire to apply to build the application we but created. In this case, information technology'due south going to exist on web, so we cull web:

Create Web Platform Firebase React

Side by side, we enter a name to annals the app. Since I'm not going to host the app on Firebase, I'll skip that and click on Register app:

Register Firebase Web App

Next, we'll initialize a new React app and add Firebase to the project with the credentials provided:

Initialize Firebase React App

Create a new React app

Create a new React app with the command below:

npx create-react-app app-name        

Adjacent, install Firebase as follows:

npm install firebase        

Create a new file in the src folder called firebase.js. Copy the configuration lawmaking from when we created a Firebase projection and paste it in the firebase.js file.

Initialize the Firebase app using the config object containing the credentials and export it. Yous'll also export a reference to the storage service, which is used to create references in your storage:

// Import the functions you lot need from the SDKs you demand import { initializeApp } from "firebase/app"; import { getStorage } from "firebase/storage"; // TODO: Add SDKs for Firebase products that you desire to utilise // https://firebase.google.com/docs/spider web/setup#bachelor-libraries // Your web app's 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:spider web:74cc537cd214fb923a750a" }; // Initialize Firebase export const app = initializeApp(firebaseConfig); export const storage = getStorage(app);        

In App.js, permit's create a form for uploading files and a push button for submitting:

import './App.css'; function App() {   render (     <div className="App">       <form className='form'>         <input type='file' />         <button type='submit'>Upload</button>       </form>     </div>   ); } export default App;        

Create Upload Button Submitting

Create a Deject Storage bucket

To apply any of the Firebase services in your app, you take to set up them up for that item project in Firebase Console. Therefore, Firebase knows that this app is using said product.

After copying the config code in Firebase console, click on Go to panel. We'll be shown an interface listing all the products we could utilise. On the left menu bar, click Storage:

Create Cloud Storage Bucket

Click on Get Started:

Firebase Storage Get Started

For the purpose of this demo, we'll choose test mode. But for production applications, yous should choose production mode to limit who can read and write to the storage. Click Next:

Firebase Test Mode Production Mode

Select Deject Storage location and click Done:

Cloud Storage Location

Now, nosotros tin can programmatically upload files to the Cloud Storage saucepan and also read those files:

Read Upload File Firebase Cloud Storage

Programmatically upload and read files

With that, everything is set up for us to write the code for uploading files. In App.js, we'll commencement by importing the storage we exported from the Firebase config file, the methods nosotros'll utilise from firebase/storage, and the React useState Hook:

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(nothing); const [progresspercent, setProgresspercent] = useState(0);  const handleSubmit = (due east) => {     eastward.preventDefault()     const file = due east.target[0]?.files[0]      if (!file) render;      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);       },       (mistake) => {         alert(error);       },       () => {         getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {           setImgUrl(downloadURL)         });       }     );   }        

Allow's break down what is occurring in the handleSubmit function. We initialized two states for the image URL after we read the uploaded file and the progress value every bit the prototype is beingness uploaded.

const file = east.target[0]?.files[0] created a variable and saved the supplied file to it.

Next, we created a reference to the file we want to operate on by calling the ref() on the case of the storage service we already created in the config file. Equally the 2d parameter, we passed in a path nosotros want the ref to bespeak to, which is optional.

Once the reference has been created, we can upload a file by calling the uploadBytesResumable(). It takes the reference we created earlier and then the file to be uploaded to cloud storage. Annotation that uploadBytes() does exactly the same thing, so either ane can be used.

Yet, with uploadBytesResumable(), the upload can be paused and resumed, and it exposes progress updates. We utilize it here because nosotros desire to brandish the progress of the upload equally it's ongoing. If you don't want that functionality, feel free to useuploadBytes().

Side by side, we phone call the on() method on the promise returned from calling uploadBytesResumable() to heed for state changes, errors, and successful uploads. These iii callback functions are run at different stages of the file upload. The first runs during the upload to notice state change events like progress, pause, and resume, while the side by side one is triggered when in that location is an unsuccessful upload. Finally, the last is run when the upload completes successfully.

On successful upload, we call the getDownloadURL() to get the download URL of the file to display on the app. Nosotros and then update country with the new image URL downloaded.

The full code for displaying the image 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 = (e) => {     e.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.circular((snapshot.bytesTransferred / snapshot.totalBytes) * 100);         setProgresspercent(progress);       },       (error) => {         alert(error);       },       () => {         getDownloadURL(uploadTask.snapshot.ref).and so((downloadURL) => {           setImgUrl(downloadURL)         });       }     );   }    return (     <div className="App">       <course onSubmit={handleSubmit} className='form'>         <input type='file' />         <push button type='submit'>Upload</push>       </form>       {         !imgUrl &&         <div className='outerbar'>           <div className='innerbar' manner={{ width: `${progresspercent}%` }}>{progresspercent}%</div>         </div>       }       {         imgUrl &&         <img src={imgUrl} alt='uploaded file' peak={200} />       }     </div>   ); } export default App;        

Determination

Firebase Cloud storage is very easy to utilize for storing different media types. In addition, it automatically scales, so you lot don't have to worry virtually moving to another provider when your data gets too large.

Cheers for reading. I hope y'all constitute this tutorial helpful in some way. Feel complimentary to inquire whatsoever questions in the comments below. Happy coding!

LogRocket: Full visibility into your web apps

LogRocket Dashboard Free Trial Banner

LogRocket is a frontend awarding monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets y'all replay the session to chop-chop empathize what went wrong. Information technology works perfectly with whatsoever app, regardless of framework, and has plugins to log boosted context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console 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 page, recreating pixel-perfect videos of even the almost complex single-page apps.

Endeavour it for free.

smithphly1938.blogspot.com

Source: https://blog.logrocket.com/firebase-cloud-storage-firebase-v9-react/

0 Response to "React Native Uploading Files to Google Cloud"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel