Uploading Files and Images to Firebase Cloud Storage in React Native

React Native Firebase Cloud Storage

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

So Let’s 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 as photos or videos. It is similar like a AWS S3 which can be used to store the files and other contents.

If you are using Firebase Cloud Storage then your data will be stored on Google Cloud Storage bucket, an exabyte scale object storage solution with high availability and global redundancy. Integration of Firebase storage is damn easy and once you 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, just 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 can either point to a specific file or to a higher level node in the hierarchy.

The Storage module also provides support for multiple buckets. A common use-case for Cloud 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 need 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 not exist yet. To create a reference, use the ref method

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

You can also 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 information such as the current upload progress:

const task = 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 also 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, you need to 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 use the list method.

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

Example Description

In this example we will create a home screen with multiple options to navigate to any screen. We will have once screen which will help us to pick a file and upload the selected file. We will also create a screen to list the files in any bucket. So Let’s see the setup and code for that.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you 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 you want to start a new project with a specific React Native version, you can use the --version argument:

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

This will make a project structure with an index file named App.js in your project 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 have specially made a separate post in detail for this where you will see point 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 next step.

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

Installation of Dependencies

To install the dependencies open the terminal and jump into your project using

cd ProjectName

For the React Native Firebase we need to install and setup the app module

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

Now install the storage module

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

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

npm install react-native-document-picker --save

That is enough for the cloud storage but in this example we will also 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-community/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 just to update the dependency in your package.json file.

CocoaPods Installation

After the updation of React Native 0.60, they have introduced autolinking so we do not require to link the library but 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, then click Get started.
  • Review the messaging about securing your Storage data using security rules. During development, consider setting up your rules for public access.
  • Select a location for your default Storage bucket.
    • This location setting is your project’s default Google Cloud Platform (GCP) resource 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 Cloud Scheduler).
    • If you aren’t able to select a location, then your project already has a default GCP resource location. It was set either during project creation or when setting up another service that requires a location setting.
    • If you’re on the Blaze plan, you can create multiple buckets, each with its own location.
    • Warning: After you set your project’s default GCP resource location, you cannot change it.
  • Click Done.

Set up public access

Cloud Storage for Firebase provides a declarative rules language that allows you to define how your data should be structured, how it should be indexed, and when your data can be read from and written to. By default, read and write access to Storage is restricted so only authenticated users 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, even people not using your app, so be sure to restrict your Storage again when you set up authentication.

For this example we will set public access and to that open storage option from console, click on rules, update with following rule and publish

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth == null; 
    }
  }
}

react_native_firebase_cloud_storage_security_rules

Project Structure for React Native Cloud Storage

Please create the following project structure and copy the code given below.

react_native_firebase_cloud_storage_file_structure.png

You can see

  1. App.js contains main Navigation
  2. HomeScreen.js, will have different 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 App.js in any code 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 = () => {
  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 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 Cloud Storage in React Native
// https://aboutreact.com/react-native-firebase-cloud-storage/

// Import React in our code
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={(style = 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 style={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: 1,
    backgroundColor: "#fff",
  },
  innerContainer: {
    flex: 1,
    alignItems: "center",
    padding: 35,
  },
  titleText: {
    fontSize: 20,
    fontWeight: "bold",
    textAlign: "center",
    padding: 20,
  },
  buttonTextStyle: {
    color: "white",
    fontWeight: "bold",
  },
  buttonStyle: {
    alignItems: "center",
    backgroundColor: "orange",
    padding: 10,
    width: "100%",
    marginTop: 16,
  },
  footerHeading: {
    fontSize: 18,
    textAlign: "center",
    color: "grey",
  },
  footerText: {
    fontSize: 16,
    textAlign: "center",
    color: "grey",
  },
});

pages/UploadFileScreen.js

// #3 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 } 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 = () => {
  // State Defination
  const [loading, setLoading] = useState(false);
  const [filePath, setFilePath] = useState({});
  const [process, setProcess] = useState("");

  const _chooseFile = async () => {
    // Opening Document Picker to select one file
    try {
      const fileDetails = await DocumentPicker.pick({
        // Provide which type of file you want user to pick
        type: [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 Error: " + JSON.stringify(error)
      );
    }
  };

  const _uploadFile = async () => {
    try {
      // Check if file selected
      if (Object.keys(filePath).length == 0)
        return alert("Please Select any File");
      setLoading(true);

      // 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.replace("file://", "")
      );
      // You can do different operation with task
      // task.pause();
      // task.resume();
      // task.cancel();

      task.on("state_changed", (taskSnapshot) => {
        setProcess(
          `${taskSnapshot.bytesTransferred} transferred 
           out of ${taskSnapshot.totalBytes}`
        );
        console.log(
          `${taskSnapshot.bytesTransferred} transferred 
           out of ${taskSnapshot.totalBytes}`
        );
      });
      task.then(() => {
        alert("Image uploaded to the bucket!");
        setProcess("");
      });
      setFilePath({});
    } catch (error) {
      console.log("Error->", error);
      alert(`Error-> ${error}`);
    }
    setLoading(false);
  };

  return (
    <>
      {loading ? (
        <View style={styles.container}>
          <ActivityIndicator size="large" color="#0000ff" />
        </View>
      ) : (
        <SafeAreaView style={{ flex: 1 }}>
          <View style={styles.container}>
            <Text style={styles.titleText}>
              Upload Input Text as File on FireStorage
            </Text>
            <View style={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
                    : 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 style={styles.footerText}>
              www.aboutreact.com
            </Text>
          </View>
        </SafeAreaView>
      )}
    </>
  );
};

export default UploadFileScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    padding: 10,
  },
  titleText: {
    fontSize: 20,
    fontWeight: "bold",
    textAlign: "center",
    padding: 20,
  },
  buttonStyle: {
    alignItems: "center",
    backgroundColor: "orange",
    padding: 10,
    width: 300,
    marginTop: 16,
  },
  buttonTextStyle: {
    color: "white",
    fontWeight: "bold",
  },
  footerHeading: {
    fontSize: 18,
    textAlign: "center",
    color: "grey",
  },
  footerText: {
    fontSize: 16,
    textAlign: "center",
    color: "grey",
  },
});

pages/FilesListingScreen.js

// #3 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 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.list({ pageToken }).then((result) => {
      result.items.forEach((ref) => {
        console.log("ref  ->>  ", JSON.stringify(ref));
      });

      if (result.nextPageToken) {
        return listFilesAndDirectories(
          reference,
          result.nextPageToken
        );
      }
      setListData(result.items);
      setLoading(false);
    });
  };

  const ItemView = ({ item }) => {
    return (
      // FlatList Item
      <View style={{ padding: 10 }}>
        <Text
          style={styles.item}
          onPress={() => getItem(item.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 Item Separator
      <View
        style={{
          height: 0.5,
          width: "100%",
          backgroundColor: "#C8C8C8",
        }}
      />
    );
  };

  const getItem = async (fullPath) => {
    const url = await storage()
      .ref(fullPath)
      .getDownloadURL()
      .catch((e) => {
        console.error(e);
      });
    Linking.openURL(url);
    console.log(url);
  };

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.titleText}>
        Listing of Files from Cloud Storage
      </Text>
      {loading ? (
        <View style={styles.container}>
          <ActivityIndicator size="large" color="#0000ff" />
        </View>
      ) : (
        <FlatList
          data={listData}
          //data defined in constructor
          ItemSeparatorComponent={ItemSeparatorView}
          //Item Separator View
          renderItem={ItemView}
          keyExtractor={(item, index) => index.toString()}
        />
      )}
      <Text style={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: 10,
  },
  titleText: {
    fontSize: 20,
    fontWeight: "bold",
    textAlign: "center",
    padding: 20,
  },
  footerHeading: {
    fontSize: 18,
    textAlign: "center",
    color: "grey",
  },
  footerText: {
    fontSize: 16,
    textAlign: "center",
    color: "grey",
  },
});

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

To run the project on an Android Virtual Device or on real debugging device

react-native run-android

or on the iOS Simulator by running (macOS only)

react-native run-ios

Download Source Code

Output Screenshots

react_native_firebase_cloud_storage1   react_native_firebase_cloud_storage2   react_native_firebase_cloud_storage3   react_native_firebase_cloud_storage4

react_native_firebase_cloud_storage5

react_native_firebase_cloud_storage6   react_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 have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂

4 thoughts on “Uploading Files and Images to Firebase Cloud Storage in React Native”

  1. Hi, When i Upload file on android device i get this error:
    “Permission Denial: reading com.android.providers.media.MediaDocumentsProvider uri content://com.android.providers.media.documents/document/image:52845 from pid=6048, uid=10198 requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs”.
    Can you help me ?

    Reply
  2. when i try to upload i get this error

    Possible Unhandled Promise Rejection (id: 1):
    Error: [storage/unknown] Permission Denial: reading com.android.externalstorage.ExternalStorageProvider uri content://com.android.externalstorage.documents/document/primary:FMWhatsApp/Media/FMWhatsApp Documents/finaltranscriptform.pdf from pid=17590, uid=10184 requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.