Cannot Upload Current Existing Photos to S3 Cloud React Native

Contents

  • 1 React Native Firebase Cloud Storage
  • 2 Firebase Deject Storage
  • 3 Create Reference and Upload/Download
  • four Example Clarification
  • 5 To Brand a React Native App
  • half-dozen Integration of Firebase SDK
  • 7 Installation of Dependencies
  • 8 CocoaPods Installation
  • 9 Create a Default Storage Bucket
  • 10 Set upwardly public access
  • 11 Projection Structure for React Native Cloud Storage
  • 12 Code to Integrate Cloud Storage in React Native
    • 12.i App.js
    • 12.2 pages/HomeScreen.js
    • 12.3 pages/UploadFileScreen.js
    • 12.4 pages/FilesListingScreen.js
  • thirteen To Run the React Native App
  • 14 Output Screenshots

React Native Firebase Cloud Storage

This is the third post of our React Native Firebase serial, in this example we will see what is Firebase Cloud Storage? and how to integrate Deject Storage in React Native App? In this example nosotros volition see how to upload file or image on deject storage, list the uploaded files and share/open the uploaded files using React Native Too.

So Allow'southward start with the Firebase Cloud Storage Example.

Firebase Cloud Storage

Storage is built for app developers who need to store and serve user-generated content, such equally photos or videos. Information technology is like like a AWS S3 which tin can be used to store the files and other contents.

If you are using Firebase Deject Storage then your information will be stored on Google Cloud Storage bucket, an exabyte scale object storage solution with loftier availability and global redundancy. Integration of Firebase storage is damn easy and once yous integrate the same in your app you can securely upload whatsoever files straight from mobile devices to Cloud Fire storage

Firebase Deject Storage buckets are presented in a hierarchical construction, only like a file system. By creating a reference to a file, your app gains access to it. These references can then be used to upload or download data, get or update metadata or delete the file. A reference tin can either point to a specific file or to a higher level node in the hierarchy.

The Storage module likewise provides back up for multiple buckets. A common use-instance for Deject Storage is to use it as a global Content Delivery Network (CDN) for your images.

Create Reference and Upload/Download

To upload any file or image on Firebase Cloud Storage you demand to import the storage

          import storage from '@react-native-firebase/storage';        

and have to create a reference, A reference is a local pointer to some file on your bucket. This can either be a file which already exists, or one which does non be yet. To create a reference, utilize the ref method

          const reference = storage().ref('my-file.txt');        

You tin can likewise specify a file located in a securely 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 Job, which if required, allows you to hook into information such as 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(() => {   console.log('Image uploaded to the bucket!'); });        

A task likewise provides the ability to pause & resume on-going operations

          task.pause(); task.resume();        

When uploading files to a bucket, they are not automatically available for consumption via a HTTP URL. To generate a new Download URL, yous demand to telephone call the getDownloadURL method on a reference:

          const url = await storage()   .ref('images/profile-1.png')   .getDownloadURL();        

If you wish to view a full list of the current files & directories within a particular bucket reference, you can utilize the list method.

          reference.list().then((result) => {     setListData(result.items); });        

Example Clarification

In this example we volition create a domicile screen with multiple options to navigate to whatever screen. We will have in one case screen which will help u.s.a. to pick a file and upload the selected file. We will also create a screen to listing the files in any bucket. So Allow'southward come across the setup and code for that.

To Make a React Native App

Getting started with React Native volition help you to know more than about the way you lot can make a React Native projection. We are going to use react-native init to brand our React Native App. Assuming that y'all have node installed, y'all tin can use npm to install the react-native-cli command line utility. Open the terminal and go 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 y'all want to start a new project with a specific React Native version, you tin use the --version argument:

          react-native init ProjectName --version X.XX.X        
          react-native init ProjectName --version react-native@next        

This will brand a projection construction with an index file named App.js in your project directory.

Integration of Firebase SDK

For starting with any of the React Native Firebase Instance yous will need to integrate Firebase in your app, I have especially made a split postal service in detail for this where you will see indicate to point process to add Firebase in your React Native App for Android and iOS both.

Please visit How to Integrate Firebase in Android and iOS App and come back for the adjacent step.

Once you are done with the Firebase integration y'all can install the further dependencies.

Installation of Dependencies

To install the dependencies open the concluding and jump into your projection using

          cd ProjectName        

For the React Native Firebase nosotros demand to install and setup the app module

          npm install @react-native-firebase/app --salve        

Now install the storage module

          npm install @react-native-firebase/storage --save        

Next, nosotros are going to use the document picker to choice the file which we will upload to Firebase Deject Storage, To use document picker install following dependency

          npm install react-native-document-picker --salvage        

That is enough for the cloud storage but in this example we will also use React Navigation as nosotros are going to switch the screens and 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-prophylactic-surface area-context @react-native-community/masked-view --save        
          npm install @react-navigation/stack --save        

This command will copy all the dependencies into your node_module directory. –salve is optional, it is just to update the dependency in your package.json file.

CocoaPods Installation

Subsequently the updation of React Native 0.threescore, they have introduced autolinking then we practice not crave to link the library only for iOS we need to install the pods. So to install the pods use

          cd ios/ && pod install --repo-update && cd ..        

Create a Default Storage Bucket

  • From the navigation pane of the Firebase console, select Storage, so click Get started.
  • Review the messaging about securing your Storage data using security rules. During evolution, consider setting up your rules for public admission.
  • Select a location for your default Storage bucket.
    • This location setting is your project's default Google Cloud Platform (GCP) resources location. Note that this location will be used for GCP services in your project that require a location setting, specifically, your Cloud Firestore database and your App Engine app (which is required if you use Deject Scheduler).
    • If y'all aren't able to select a location, then your project already has a default GCP resources location. It was set either during project creation or when setting upward another service that requires a location setting.
    • If you're on the Blaze programme, you tin create multiple buckets, each with its own location.
    • Alert: Afterward you lot set your projection's default GCP resource location, you cannot modify it.
  • Click Washed.

Prepare public admission

Deject Storage for Firebase provides a declarative rules language that allows yous to define how your data should be structured, how information technology should be indexed, and when your data can exist read from and written to. By default, read and write access to Storage is restricted so merely authenticated users tin can read or write data. To get started without setting up Authentication, you can configure your rules for public access.

This does make Storage open to anyone, fifty-fifty people non using your app, so exist sure to restrict your Storage again when y'all set upward authentication.

For this example we will set public access and to that open storage choice from panel, click on rules, update with post-obit rule and publish

            rules_version = 'ii'; service firebase.storage {   match /b/{saucepan}/o {     lucifer /{allPaths=**} {       allow read, write: if request.auth == aught;      }   } }          

react_native_firebase_cloud_storage_security_rules

Projection Structure for React Native Cloud Storage

Please create the post-obit project structure and copy the code given below.

react_native_firebase_cloud_storage_file_structure.png

You can meet

  1. App.js contains chief Navigation
  2. HomeScreen.js, will have unlike options to open different screens
  3. FileListingScreen.js, To list all the files from Cloud Storage
  4. UploadFileScreen.js, To pick and upload the file on Cloud Storage

Code to Integrate Cloud Storage in React Native

Please open up App.js in whatsoever lawmaking editor and replace the code with the following code

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 = () => {   render (     <NavigationContainer>       <Stack.Navigator         initialRouteName="HomeScreen"         screenOptions={{           headerStyle: {             backgroundColor: "orange", //Prepare Header colour           },           headerTintColor: "#fff", //Set Header text color           headerTitleStyle: {             fontWeight: "bold", //Gear up Header text style           },         }}       >         <Stack.Screen           name="HomeScreen"           component={HomeScreen}           options={{ title: "Home" }}         />         <Stack.Screen           name="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 nosotros are going to utilize import {   SafeAreaView,   StyleSheet,   View,   Text,   TouchableOpacity, } from "react-native";  const HomeScreen = (props) => {   render (     <SafeAreaView mode={(fashion = styles.container)}>       <View style={styles.innerContainer}>         <Text style={styles.titleText}>           Uploading Files and Images to Firebase Cloud           Storage in React Native         </Text>         <TouchableOpacity           style={styles.buttonStyle}           onPress={() =>             props.navigation.navigate("UploadFileScreen")           }         >           <Text fashion={styles.buttonTextStyle}>             Upload File           </Text>         </TouchableOpacity>         <TouchableOpacity           mode={styles.buttonStyle}           onPress={() =>             props.navigation.navigate("FilesListingScreen")           }         >           <Text style={styles.buttonTextStyle}>             Uploaded File Listing           </Text>         </TouchableOpacity>       </View>       <Text style={styles.footerHeading}>         React Native Firebase Deject Storage       </Text>       <Text style={styles.footerText}>         world wide web.aboutreact.com       </Text>     </SafeAreaView>   ); };  export default HomeScreen;  const styles = StyleSheet.create({   container: {     flex: 1,     backgroundColor: "#fff",   },   innerContainer: {     flex: 1,     alignItems: "center",     padding: 35,   },   titleText: {     fontSize: xx,     fontWeight: "bold",     textAlign: "middle",     padding: twenty,   },   buttonTextStyle: {     colour: "white",     fontWeight: "bold",   },   buttonStyle: {     alignItems: "center",     backgroundColor: "orange",     padding: x,     width: "100%",     marginTop: 16,   },   footerHeading: {     fontSize: 18,     textAlign: "centre",     color: "grey",   },   footerText: {     fontSize: 16,     textAlign: "center",     color: "greyness",   }, });        

pages/UploadFileScreen.js

          // #iii Uploading Files and Images to Firebase Deject Storage in React Native // https://aboutreact.com/react-native-firebase-deject-storage/  // Import React in our code 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 organization import DocumentPicker from "react-native-document-picker";  const UploadFileScreen = () => {   // State Defination   const [loading, setLoading] = useState(false);   const [filePath, setFilePath] = useState({});   const [process, setProcess] = useState("");    const _chooseFile = async () => {     // Opening Document Picker to select i file     try {       const fileDetails = await DocumentPicker.pick({         // Provide which blazon of file you want user to pick         blazon: [DocumentPicker.types.allFiles],       });       console.log(         "fileDetails : " + JSON.stringify(fileDetails)       );       // Setting the state for selected File       setFilePath(fileDetails);     } catch (error) {       setFilePath({});       // If user canceled the document selection       alert(         DocumentPicker.isCancel(error)           ? "Canceled"           : "Unknown Fault: " + JSON.stringify(error)       );     }   };    const _uploadFile = async () => {     try {       // Cheque if file selected       if (Object.keys(filePath).length == 0)         return alert("Please Select whatsoever File");       setLoading(true);        // Create Reference       panel.log(filePath.uri.replace("file://", ""));       console.log(filePath.proper name);       const reference = storage().ref(         `/myfiles/${filePath.name}`       );        // Put File       const task = reference.putFile(         filePath.uri.replace("file://", "")       );       // You can do different operation with task       // task.interruption();       // chore.resume();       // job.cancel();        task.on("state_changed", (taskSnapshot) => {         setProcess(           `${taskSnapshot.bytesTransferred} transferred             out of ${taskSnapshot.totalBytes}`         );         panel.log(           `${taskSnapshot.bytesTransferred} transferred             out of ${taskSnapshot.totalBytes}`         );       });       task.then(() => {         alert("Image uploaded to the saucepan!");         setProcess("");       });       setFilePath({});     } catch (mistake) {       console.log("Error->", fault);       alarm(`Fault-> ${error}`);     }     setLoading(imitation);   };    return (     <>       {loading ? (         <View style={styles.container}>           <ActivityIndicator size="large" colour="#0000ff" />         </View>       ) : (         <SafeAreaView manner={{ flex: 1 }}>           <View manner={styles.container}>             <Text style={styles.titleText}>               Upload Input Text as File on FireStorage             </Text>             <View fashion={styles.container}>               <Text>                 Choose File and Upload to FireStorage               </Text>               <Text>{process}</Text>               <TouchableOpacity                 activeOpacity={0.5}                 style={styles.buttonStyle}                 onPress={_chooseFile}               >                 <Text style={styles.buttonTextStyle}>                   Choose Image (Current Selected:{" "}                   {Object.keys(filePath).length == 0                     ? 0                     : i}                   )                 </Text>               </TouchableOpacity>               <TouchableOpacity                 way={styles.buttonStyle}                 onPress={_uploadFile}               >                 <Text manner={styles.buttonTextStyle}>                   Upload File on FireStorage                 </Text>               </TouchableOpacity>             </View>             <Text style={styles.footerHeading}>               React Native Firebase Deject Storage             </Text>             <Text style={styles.footerText}>               world wide web.aboutreact.com             </Text>           </View>         </SafeAreaView>       )}     </>   ); };  export default UploadFileScreen;  const styles = StyleSheet.create({   container: {     flex: ane,     backgroundColor: "#fff",     alignItems: "center",     padding: x,   },   titleText: {     fontSize: 20,     fontWeight: "bold",     textAlign: "center",     padding: 20,   },   buttonStyle: {     alignItems: "center",     backgroundColor: "orange",     padding: 10,     width: 300,     marginTop: xvi,   },   buttonTextStyle: {     colour: "white",     fontWeight: "assuming",   },   footerHeading: {     fontSize: 18,     textAlign: "heart",     color: "grey",   },   footerText: {     fontSize: 16,     textAlign: "center",     color: "gray",   }, });        

pages/FilesListingScreen.js

          // #iii Uploading Files and Images to Firebase Cloud 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 nosotros are going to utilise import {   SafeAreaView,   StyleSheet,   Text,   View,   ActivityIndicator,   FlatList,   Linking, } from "react-native";  import storage from "@react-native-firebase/storage"; const FilesListingScreen = () => {   // Country Defination   const [listData, setListData] = useState([]);   const [loading, setLoading] = useState(true);    useEffect(() => {     listFilesAndDirectories("");   }, []);    const listFilesAndDirectories = (pageToken) => {     const reference = storage().ref("myfiles");     reference.list({ pageToken }).then((effect) => {       result.items.forEach((ref) => {         console.log("ref  ->>  ", JSON.stringify(ref));       });        if (result.nextPageToken) {         return listFilesAndDirectories(           reference,           effect.nextPageToken         );       }       setListData(outcome.items);       setLoading(imitation);     });   };    const ItemView = ({ item }) => {     return (       // FlatList Item       <View style={{ padding: 10 }}>         <Text           fashion={styles.particular}           onPress={() => getItem(detail.fullPath)}         >           File Name: {item.name}           {"\due north"}           File Total Path: {item.fullPath}           {"\northward"}           Bucket: {detail.bucket}         </Text>         <Text style={{ color: "reddish" }}>           Click to generate Signed URL and Open up information technology in           browser         </Text>       </View>     );   };    const ItemSeparatorView = () => {     return (       // FlatList Item Separator       <View         style={{           acme: 0.v,           width: "100%",           backgroundColor: "#C8C8C8",         }}       />     );   };    const getItem = async (fullPath) => {     const url = await storage()       .ref(fullPath)       .getDownloadURL()       .catch((due east) => {         console.mistake(e);       });     Linking.openURL(url);     console.log(url);   };    return (     <SafeAreaView mode={styles.container}>       <Text style={styles.titleText}>         Listing of Files from Cloud Storage       </Text>       {loading ? (         <View way={styles.container}>           <ActivityIndicator size="large" color="#0000ff" />         </View>       ) : (         <FlatList           data={listData}           //data divers in constructor           ItemSeparatorComponent={ItemSeparatorView}           //Item Separator View           renderItem={ItemView}           keyExtractor={(item, index) => alphabetize.toString()}         />       )}       <Text style={styles.footerHeading}>         React Native Firebase Cloud Storage       </Text>       <Text way={styles.footerText}>         www.aboutreact.com       </Text>     </SafeAreaView>   ); };  export default FilesListingScreen;  const styles = StyleSheet.create({   container: {     flex: 1,     backgroundColor: "#fff",     padding: x,   },   titleText: {     fontSize: 20,     fontWeight: "bold",     textAlign: "center",     padding: 20,   },   footerHeading: {     fontSize: eighteen,     textAlign: "center",     color: "greyness",   },   footerText: {     fontSize: 16,     textAlign: "center",     color: "grayness",   }, });        

To Run the React Native App

Open up the terminal once more and jump 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 merely)

          react-native run-ios        

Download Source Lawmaking

Output Screenshots

react_native_firebase_cloud_storage1 react_native_firebase_cloud_storage2react_native_firebase_cloud_storage3 react_native_firebase_cloud_storage4

react_native_firebase_cloud_storage5

react_native_firebase_cloud_storage6react_native_firebase_cloud_storage7

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 you accept any doubts or you want to share something almost the topic you can annotate beneath or contact united states of america hither. There volition be more posts coming presently. Stay tuned!

Hope you liked it. 🙂

moodyfark1973.blogspot.com

Source: https://aboutreact.com/react-native-firebase-cloud-storage/

0 Response to "Cannot Upload Current Existing Photos to S3 Cloud React Native"

Enregistrer un commentaire

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel