Upload Photo to Cloud and Save Link to Sqlite React
Contents
- 1 React Native Firebase Cloud Storage
- 2 Firebase Cloud Storage
- 3 Create Reference and Upload/Download
- 4 Example Clarification
- 5 To Make a React Native App
- six Integration of Firebase SDK
- 7 Installation of Dependencies
- 8 CocoaPods Installation
- 9 Create a Default Storage Saucepan
- 10 Gear up up public access
- 11 Project Structure for React Native Cloud Storage
- 12 Lawmaking to Integrate Deject Storage in React Native
- 12.1 App.js
- 12.2 pages/HomeScreen.js
- 12.three pages/UploadFileScreen.js
- 12.iv pages/FilesListingScreen.js
- 13 To Run the React Native App
- xiv Output Screenshots
React Native Firebase Cloud Storage
This is the third post of our React Native Firebase series, in this example we will meet what is Firebase Cloud Storage? and how to integrate Cloud Storage in React Native App? In this case we volition run across how to upload file or paradigm on deject storage, list the uploaded files and share/open the uploaded files using React Native Besides.
So Let's get-go with the Firebase Cloud Storage Example.
Firebase Deject Storage
Storage is built for app developers who need to store and serve user-generated content, such as photos or videos. It is similar like a AWS S3 which can exist used to store the files and other contents.
If you are using Firebase Deject Storage then your data will be stored on Google Deject Storage saucepan, an exabyte scale object storage solution with loftier availability and global redundancy. Integration of Firebase storage is damn piece of cake and once you lot integrate the same in your app you can securely upload any files directly from mobile devices to Cloud Fire storage
Firebase Cloud Storage buckets are presented in a hierarchical structure, merely like a file system. By creating a reference to a file, your app gains access to information technology. These references can and so be used to upload or download data, become or update metadata or delete the file. A reference can either point to a specific file or to a higher level node in the hierarchy.
The Storage module too provides back up for multiple buckets. A common utilise-example for Deject Storage is to utilize it as a global Content Delivery Network (CDN) for your images.
Create Reference and Upload/Download
To upload whatever file or image on Firebase Cloud Storage you need to import the storage
import storage from '@react-native-firebase/storage'; and have to create a reference, A reference is a local arrow to some file on your bucket. This can either exist a file which already exists, or one which does not exist yet. To create a reference, use the ref method
const reference = storage().ref('my-file.txt'); You can likewise specify a file located in a deeply nested directory:
const reference = storage().ref('/myfiles/mycollection/my-file.txt'); To upload a file directly from the users device, the putFile method on a reference accepts a string path to the file on the users device.
const task = reference.putFile(localFilePath); The putFile method returns a Task, which if required, allows you to hook into data such equally the current upload progress:
const chore = reference.putFile(pathToFile); task.on('state_changed', taskSnapshot => { console.log(`${taskSnapshot.bytesTransferred} transferred out of ${taskSnapshot.totalBytes}`); }); task.then(() => { panel.log('Image uploaded to the bucket!'); }); A task also provides the ability to pause & resume on-going operations
chore.suspension(); task.resume(); When uploading files to a saucepan, they are not automatically available for consumption via a HTTP URL. To generate a new Download URL, you need to call the getDownloadURL method on a reference:
const url = await storage() .ref('images/profile-i.png') .getDownloadURL(); If you wish to view a total listing of the current files & directories within a particular saucepan reference, you tin can use the list method.
reference.list().then((upshot) => { setListData(upshot.items); }); Example Description
In this example we volition create a home screen with multiple options to navigate to any screen. We will have once screen which will assistance us to pick a file and upload the selected file. Nosotros volition likewise create a screen to listing the files in any saucepan. So Let's see the setup and code for that.
To Brand a React Native App
Getting started with React Native will assistance you lot to know more about the way you tin make a React Native project. We are going to use react-native init to make our React Native App. Assuming that yous accept node installed, yous can employ npm to install the react-native-cli command line utility. Open the final and get to the workspace and run
npm install -g react-native-cli Run the following commands to create a new React Native project
react-native init ProjectName If you lot want to start a new project with a specific React Native version, y'all can use the --version statement:
react-native init ProjectName --version X.XX.X react-native init ProjectName --version react-native@next This will make a projection structure with an index file named App.js in your projection directory.
Integration of Firebase SDK
For starting with any of the React Native Firebase Example you will need to integrate Firebase in your app, I accept especially made a split up postal service in item for this where yous volition see bespeak to point process to add together Firebase in your React Native App for Android and iOS both.
Please visit How to Integrate Firebase in Android and iOS App and come up back for the next stride.
Once you are washed with the Firebase integration you tin can install the further dependencies.
Installation of Dependencies
To install the dependencies open up the terminal and jump into your projection using
cd ProjectName For the React Native Firebase nosotros need to install and setup the app module
npm install @react-native-firebase/app --save At present install the storage module
npm install @react-native-firebase/storage --save Next, we are going to utilise the document picker to selection the file which nosotros will upload to Firebase Cloud Storage, To use document picker install following dependency
npm install react-native-document-picker --save That is plenty for the cloud storage but in this instance we will likewise use React Navigation as we are going to switch the screens so install the following react-navigation dependencies also
npm install @react-navigation/native --save Other supporting libraries for react-navigation
npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-customs/masked-view --save npm install @react-navigation/stack --save This command will copy all the dependencies into your node_module directory. –save is optional, it is only to update the dependency in your bundle.json file.
CocoaPods Installation
After the updation of React Native 0.60, they take introduced autolinking and so we practise not crave to link the library but for iOS nosotros need to install the pods. And so to install the pods employ
cd ios/ && pod install --repo-update && cd .. Create a Default Storage Bucket
- From the navigation pane of the Firebase console, select Storage, so click Go started.
- Review the messaging about securing your Storage data using security rules. During evolution, consider setting upward your rules for public access.
- Select a location for your default Storage bucket.
- This location setting is your projection's default Google Deject Platform (GCP) resource location. Note that this location will be used for GCP services in your projection that crave a location setting, specifically, your Cloud Firestore database and your App Engine app (which is required if you lot use Cloud Scheduler).
- If yous aren't able to select a location, then your projection already has a default GCP resource location. It was fix either during project creation or when setting upwardly some other service that requires a location setting.
- If yous're on the Blaze plan, you tin create multiple buckets, each with its ain location.
- Alarm: After you set your project'southward default GCP resource location, you cannot change it.
- Click Done.
Fix public access
Cloud Storage for Firebase provides a declarative rules language that allows yous to ascertain how your data should be structured, how it should be indexed, and when your data tin can be read from and written to. By default, read and write access to Storage is restricted then only authenticated users can read or write data. To get started without setting upwards Authentication, you can configure your rules for public access.
This does make Storage open to anyone, even people not using your app, then be sure to restrict your Storage again when you set up authentication.
For this instance we will set up public access and to that open storage option from panel, click on rules, update with following dominion and publish
rules_version = '2'; service firebase.storage { friction match /b/{saucepan}/o { lucifer /{allPaths=**} { allow read, write: if request.auth == naught; } } }
Project Structure for React Native Cloud Storage
Delight create the following project construction and copy the lawmaking given below.
You can encounter
- App.js contains main Navigation
- HomeScreen.js, will have different options to open different screens
- FileListingScreen.js, To list all the files from Deject Storage
- UploadFileScreen.js, To choice and upload the file on Cloud Storage
Code to Integrate Cloud Storage in React Native
Please open up App.js in any code editor and supervene upon the lawmaking with the following lawmaking
App.js
// #3 Uploading Files and Images to Firebase Cloud Storage in React Native // https://aboutreact.com/react-native-firebase-cloud-storage/ import "react-native-gesture-handler"; import * as React from "react"; import { NavigationContainer } from "@react-navigation/native"; import { createStackNavigator } from "@react-navigation/stack"; import HomeScreen from "./pages/HomeScreen"; import UploadFileScreen from "./pages/UploadFileScreen"; import FilesListingScreen from "./pages/FilesListingScreen"; const Stack = createStackNavigator(); const App = () => { return ( <NavigationContainer> <Stack.Navigator initialRouteName="HomeScreen" screenOptions={{ headerStyle: { backgroundColor: "orange", //Set Header color }, headerTintColor: "#fff", //Set Header text color headerTitleStyle: { fontWeight: "bold", //Set Header text way }, }} > <Stack.Screen name="HomeScreen" component={HomeScreen} options={{ championship: "Home" }} /> <Stack.Screen proper noun="UploadFileScreen" component={UploadFileScreen} options={{ title: "Upload File" }} /> <Stack.Screen name="FilesListingScreen" component={FilesListingScreen} options={{ title: "Uploaded Files" }} /> </Stack.Navigator> </NavigationContainer> ); }; export default App; pages/HomeScreen.js
// #3 Uploading Files and Images to Firebase Deject Storage in React Native // https://aboutreact.com/react-native-firebase-cloud-storage/ // Import React in our lawmaking import React from "react"; // Import all the components we are going to use import { SafeAreaView, StyleSheet, View, Text, TouchableOpacity, } from "react-native"; const HomeScreen = (props) => { return ( <SafeAreaView style={(fashion = styles.container)}> <View way={styles.innerContainer}> <Text style={styles.titleText}> Uploading Files and Images to Firebase Cloud Storage in React Native </Text> <TouchableOpacity mode={styles.buttonStyle} onPress={() => props.navigation.navigate("UploadFileScreen") } > <Text fashion={styles.buttonTextStyle}> Upload File </Text> </TouchableOpacity> <TouchableOpacity style={styles.buttonStyle} onPress={() => props.navigation.navigate("FilesListingScreen") } > <Text style={styles.buttonTextStyle}> Uploaded File Listing </Text> </TouchableOpacity> </View> <Text style={styles.footerHeading}> React Native Firebase Cloud Storage </Text> <Text style={styles.footerText}> www.aboutreact.com </Text> </SafeAreaView> ); }; export default HomeScreen; const styles = StyleSheet.create({ container: { flex: i, backgroundColor: "#fff", }, innerContainer: { flex: 1, alignItems: "heart", padding: 35, }, titleText: { fontSize: xx, fontWeight: "bold", textAlign: "center", padding: 20, }, buttonTextStyle: { color: "white", fontWeight: "bold", }, buttonStyle: { alignItems: "center", backgroundColor: "orange", padding: 10, width: "100%", marginTop: sixteen, }, footerHeading: { fontSize: 18, textAlign: "heart", colour: "grayness", }, footerText: { fontSize: 16, textAlign: "center", color: "grey", }, }); pages/UploadFileScreen.js
// #3 Uploading Files and Images to Firebase Deject Storage in React Native // https://aboutreact.com/react-native-firebase-cloud-storage/ // Import React in our lawmaking import React, { useState } from "react"; // Import all the components we are going to use import { SafeAreaView, StyleSheet, Text, View, ActivityIndicator, TouchableOpacity, } from "react-native"; // Firebase Storage to upload file import storage from "@react-native-firebase/storage"; // To pick the file from local file system import DocumentPicker from "react-native-document-picker"; const UploadFileScreen = () => { // Country Defination const [loading, setLoading] = useState(false); const [filePath, setFilePath] = useState({}); const [process, setProcess] = useState(""); const _chooseFile = async () => { // Opening Certificate Picker to select one file try { const fileDetails = look DocumentPicker.pick({ // Provide which type of file you want user to pick type: [DocumentPicker.types.allFiles], }); console.log( "fileDetails : " + JSON.stringify(fileDetails) ); // Setting the country for selected File setFilePath(fileDetails); } grab (error) { setFilePath({}); // If user canceled the document selection alert( DocumentPicker.isCancel(error) ? "Canceled" : "Unknown Error: " + JSON.stringify(error) ); } }; const _uploadFile = async () => { try { // Check if file selected if (Object.keys(filePath).length == 0) return alert("Delight Select whatever File"); setLoading(truthful); // Create Reference console.log(filePath.uri.replace("file://", "")); console.log(filePath.name); const reference = storage().ref( `/myfiles/${filePath.name}` ); // Put File const task = reference.putFile( filePath.uri.supersede("file://", "") ); // You can practice different functioning with chore // task.pause(); // job.resume(); // job.cancel(); job.on("state_changed", (taskSnapshot) => { setProcess( `${taskSnapshot.bytesTransferred} transferred out of ${taskSnapshot.totalBytes}` ); console.log( `${taskSnapshot.bytesTransferred} transferred out of ${taskSnapshot.totalBytes}` ); }); task.so(() => { alert("Prototype uploaded to the bucket!"); setProcess(""); }); setFilePath({}); } catch (error) { console.log("Mistake->", mistake); alert(`Error-> ${fault}`); } setLoading(fake); }; render ( <> {loading ? ( <View style={styles.container}> <ActivityIndicator size="large" color="#0000ff" /> </View> ) : ( <SafeAreaView style={{ flex: i }}> <View mode={styles.container}> <Text way={styles.titleText}> Upload Input Text every bit File on FireStorage </Text> <View style={styles.container}> <Text> Choose File and Upload to FireStorage </Text> <Text>{process}</Text> <TouchableOpacity activeOpacity={0.five} manner={styles.buttonStyle} onPress={_chooseFile} > <Text style={styles.buttonTextStyle}> Choose Image (Current Selected:{" "} {Object.keys(filePath).length == 0 ? 0 : 1} ) </Text> </TouchableOpacity> <TouchableOpacity style={styles.buttonStyle} onPress={_uploadFile} > <Text style={styles.buttonTextStyle}> Upload File on FireStorage </Text> </TouchableOpacity> </View> <Text style={styles.footerHeading}> React Native Firebase Cloud Storage </Text> <Text way={styles.footerText}> www.aboutreact.com </Text> </View> </SafeAreaView> )} </> ); }; export default UploadFileScreen; const styles = StyleSheet.create({ container: { flex: i, backgroundColor: "#fff", alignItems: "eye", padding: ten, }, titleText: { fontSize: twenty, fontWeight: "bold", textAlign: "heart", padding: 20, }, buttonStyle: { alignItems: "eye", backgroundColor: "orange", padding: 10, width: 300, marginTop: 16, }, buttonTextStyle: { color: "white", fontWeight: "assuming", }, footerHeading: { fontSize: 18, textAlign: "center", color: "grey", }, footerText: { fontSize: 16, textAlign: "heart", color: "grey", }, }); pages/FilesListingScreen.js
// #three Uploading Files and Images to Firebase Deject Storage in React Native // https://aboutreact.com/react-native-firebase-cloud-storage/ // Import React in our code import React, { useState, useEffect } from "react"; // Import all the components we are going to use import { SafeAreaView, StyleSheet, Text, View, ActivityIndicator, FlatList, Linking, } from "react-native"; import storage from "@react-native-firebase/storage"; const FilesListingScreen = () => { // State Defination const [listData, setListData] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { listFilesAndDirectories(""); }, []); const listFilesAndDirectories = (pageToken) => { const reference = storage().ref("myfiles"); reference.listing({ pageToken }).so((effect) => { outcome.items.forEach((ref) => { console.log("ref ->> ", JSON.stringify(ref)); }); if (result.nextPageToken) { return listFilesAndDirectories( reference, consequence.nextPageToken ); } setListData(result.items); setLoading(false); }); }; const ItemView = ({ detail }) => { render ( // FlatList Particular <View mode={{ padding: x }}> <Text mode={styles.detail} onPress={() => getItem(detail.fullPath)} > File Name: {item.name} {"\n"} File Full Path: {item.fullPath} {"\n"} Bucket: {item.bucket} </Text> <Text style={{ color: "red" }}> Click to generate Signed URL and Open it in browser </Text> </View> ); }; const ItemSeparatorView = () => { return ( // FlatList Detail Separator <View fashion={{ height: 0.5, width: "100%", backgroundColor: "#C8C8C8", }} /> ); }; const getItem = async (fullPath) => { const url = expect storage() .ref(fullPath) .getDownloadURL() .grab((e) => { console.error(due east); }); Linking.openURL(url); console.log(url); }; return ( <SafeAreaView style={styles.container}> <Text way={styles.titleText}> Listing of Files from Deject Storage </Text> {loading ? ( <View style={styles.container}> <ActivityIndicator size="large" color="#0000ff" /> </View> ) : ( <FlatList information={listData} //data defined in constructor ItemSeparatorComponent={ItemSeparatorView} //Detail Separator View renderItem={ItemView} keyExtractor={(item, index) => index.toString()} /> )} <Text way={styles.footerHeading}> React Native Firebase Cloud Storage </Text> <Text style={styles.footerText}> www.aboutreact.com </Text> </SafeAreaView> ); }; export default FilesListingScreen; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#fff", padding: ten, }, titleText: { fontSize: 20, fontWeight: "bold", textAlign: "centre", padding: 20, }, footerHeading: { fontSize: xviii, textAlign: "eye", color: "greyness", }, footerText: { fontSize: 16, textAlign: "center", color: "grey", }, }); To Run the React Native App
Open the terminal once more and leap into your project using.
cd ProjectName To run the project on an Android Virtual Device or on existent debugging device
react-native run-android or on the iOS Simulator by running (macOS only)
react-native run-ios Download Source Code
Output Screenshots


That was how you can upload any file on Firebase Cloud Storage and list the files from Could Storage from React Native App for Android and iOS both. If y'all take any doubts or you lot desire to share something about the topic you can comment below or contact us here. In that location will exist more posts coming shortly. Stay tuned!
Hope you liked it. 🙂
Source: https://aboutreact.com/react-native-firebase-cloud-storage/
0 Response to "Upload Photo to Cloud and Save Link to Sqlite React"
Post a Comment