Upload a Video to Google Cloud in React Native
Firebase is a mobile and web application development platform created by Google that provides products and solutions that yous can rely on for you app development needs, including Deject Firestore, Deject Functions, Authentication, Hosting, Realtime Database, Cloud Storage, and more.
Cloud storage service is designed for developers to easily shop and serve user-generated content like photos and videos, which are stored in Google Deject Storage buckets. In addition, Firebase Cloud Storage integrates with other Firebase services like Firebase Authentication so that users can organize uploaded files and apply access controls if needed.
In this article, we'll acquire how to upload a file to Firebase Deject Storage and access the URL of the uploaded file using Firebase v9.ten,the latest version at the fourth dimension of writing. To follow along with this commodity, you'll need:
- npm and Node.js installed
- Knowledge of React and React Hooks
- A Google account to access Firebase Console
Let's become started!
Tabular array 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 Console at https://panel.firebase.google.com/. You lot'll see the homepage:
Click on the Create a Project button. Blazon in the proper name of your project. I'll proper noun mine React-Firebase-storage. Have the Firebase terms and click Go on:
If yous'd like to employ Google Analytics in your project, and then leave the Enable Google Analytics toggle on. I don't need information technology for this demo, and then I'm going to turn information technology off. Click on Create project and expect for the project to be created:
Click on Continue to go along to the console:
In the adjacent interface, we'll select the platform we want to use to build the application we just created. In this example, it'south going to be on web, so we choose spider web:
Adjacent, we enter a proper noun to register the app. Since I'k not going to host the app on Firebase, I'll skip that and click on Register app:
Side by side, we'll initialize a new React app and add together Firebase to the projection with the credentials provided:
Create a new React app
Create a new React app with the control below:
npx create-react-app app-name
Next, install Firebase as follows:
npm install firebase
Create a new file in the src folder called firebase.js. Re-create the configuration code from when we created a Firebase project and paste information technology in the firebase.js file.
Initialize the Firebase app using the config object containing the credentials and export it. Y'all'll too export a reference to the storage service, which is used to create references in your storage:
// Import the functions you demand from the SDKs you need import { initializeApp } from "firebase/app"; import { getStorage } from "firebase/storage"; // TODO: Add SDKs for Firebase products that you lot desire to utilise // https://firebase.google.com/docs/spider web/setup#available-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: "ane:1071019670975:web:74cc537cd214fb923a750a" }; // Initialize Firebase export const app = initializeApp(firebaseConfig); export const storage = getStorage(app); In App.js, let'southward create a form for uploading files and a button for submitting:
import './App.css'; role App() { render ( <div className="App"> <class className='form'> <input type='file' /> <push button type='submit'>Upload</push> </form> </div> ); } export default App;
Create a Cloud Storage saucepan
To utilise whatsoever of the Firebase services in your app, you have to set them up for that item project in Firebase Panel. Therefore, Firebase knows that this app is using said product.
After copying the config lawmaking in Firebase console, click on Go to console. We'll exist shown an interface listing all the products we could apply. On the left menu bar, click Storage:
Click on Get Started:
For the purpose of this demo, we'll cull test mode. Only for production applications, you should choose product mode to limit who tin can read and write to the storage. Click Adjacent:
Select Cloud Storage location and click Done:
Now, nosotros can programmatically upload files to the Deject Storage bucket and also read those files:
Programmatically upload and read files
With that, everything is gear up for us to write the code for uploading files. In App.js, we'll start by importing the storage nosotros exported from the Firebase config file, the methods we'll use from firebase/storage, and the React useState Claw:
import { useState } from "react"; import { storage } from './firebase'; import { ref, getDownloadURL, uploadBytesResumable } from "firebase/storage"; Allow's write a office that will run when a user hits the submit button:
const [imgUrl, setImgUrl] = useState(cypher); const [progresspercent, setProgresspercent] = useState(0); const handleSubmit = (e) => { e.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) => { alert(fault); }, () => { getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => { setImgUrl(downloadURL) }); } ); } Permit's break downwards 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 image is being uploaded.
const file = e.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. As the 2nd parameter, we passed in a path nosotros want the ref to point to, which is optional.
Once the reference has been created, nosotros tin can upload a file by calling the uploadBytesResumable(). Information technology takes the reference we created before and so the file to exist uploaded to deject storage. Note that uploadBytes() does exactly the same matter, so either 1 can be used.
However, with uploadBytesResumable(), the upload tin exist paused and resumed, and information technology exposes progress updates. We use it hither because we desire to display the progress of the upload as it'due south ongoing. If you lot don't want that functionality, feel free to useuploadBytes().
Next, we telephone call the on() method on the promise returned from calling uploadBytesResumable() to listen for state changes, errors, and successful uploads. These three callback functions are run at dissimilar stages of the file upload. The first runs during the upload to observe country alter events like progress, break, and resume, while the next one is triggered when there is an unsuccessful upload. Finally, the last is run when the upload completes successfully.
On successful upload, nosotros call the getDownloadURL() to get the download URL of the file to brandish on the app. We then update state with the new image URL downloaded.
The full code for displaying the paradigm 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(zilch); const [progresspercent, setProgresspercent] = useState(0); const handleSubmit = (e) => { e.preventDefault() const file = e.target[0]?.files[0] if (!file) render; const storageRef = ref(storage, `files/${file.proper noun}`); const uploadTask = uploadBytesResumable(storageRef, file); uploadTask.on("state_changed", (snapshot) => { const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100); setProgresspercent(progress); }, (error) => { alert(error); }, () => { getDownloadURL(uploadTask.snapshot.ref).so((downloadURL) => { setImgUrl(downloadURL) }); } ); } render ( <div className="App"> <course onSubmit={handleSubmit} className='grade'> <input type='file' /> <button type='submit'>Upload</button> </form> { !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; Decision
Firebase Cloud storage is very easy to use for storing different media types. In add-on, information technology automatically scales, so y'all don't take to worry near moving to another provider when your data gets too big.
Thanks for reading. I hope you found this tutorial helpful in some way. Experience free to ask any questions in the comments below. Happy coding!
LogRocket: Full 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 apace 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 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. It also instruments the DOM to tape the HTML and CSS on the folio, recreating pixel-perfect videos of fifty-fifty the most complex single-page apps.
Try information technology for free.
Source: https://blog.logrocket.com/firebase-cloud-storage-firebase-v9-react/
0 Response to "Upload a Video to Google Cloud in React Native"
Post a Comment