IMAGE UPLOADING IN REACT NATIVE WITH FIREBASE STORAGE

Handling image upload isn’t a trivial task. Image uploading is data and network intensive, so you need to handle it gracefully to ensure it is scalable and does not cause too much stress on the server.

For image uploading we decide to use Firebase Storage to handle heavy image uploading. Once uploaded Firebase submits the image URL to the backend server.

Firebase Storage is designed specifically for scale, security, and network resiliency:

  • Scale: every file uploaded is backed by Google Cloud Storage, which scales to petabytes.
  • Security: files can be secured to specific users or sets of users using Storage Security Rules.
  • Network resiliency: uploads and downloads are automatically retried in the case of poor network connections, so you do not have to keep track of network status.

Whilst implementing Firebase storage for the first time for a ReactNative app I thought I had hit a dead end when I read the following from the Firebase Blog:

React Native does not support the File and Blob types, so Firebase Storage uploads will not work in this environment. File downloads do work however.

Luckily, I found a module that had File and Blob types support in React Native: https://github.com/wkh237/react-native-fetch-blob

Some features sounded promising:

  • Transfer data directly from/to storage without BASE64 bridging.
  • File API supports normal files, Asset files, and CameraRoll files.
  • Native-to-native file manipulation API, reduce JS bridging performance loss.
  • File stream support for dealing with large file (Blob type).
  • Blob, File, XMLHttpRequest polyfills that make browser-based library available in React Native (experimental).

The following shows how I was able to choose photos from device and upload to Firebase Storage with firebase and react-native-fetch-blob modules

This is how the app looks once finished:

Firebase Demo

1. Init a demo project:

$ react-native init FirebaseStorageDemo

2. Install necessary modules:

$ yarn add firebase react-native-fetch-blob react-native-image-picker
$ RNFB_ANDROID_PERMISSIONS=true react-native link

The extra react-native-image-picker is for image picking.

3. Add permissions for Android:

to AndroidManifest.xml

...
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
...

4. Configure Firebase Storage:

First we need to create an images folder in the root Storage:

By default Firebase forbids read or write to the Storage folder. We need to open up permission rules.

For this demo app, I will just open up both read and write for the images folder. In real situation, you probably want to tighten the permissions.

5. Initialize Firebase based on your config:

const config = {
  apiKey: "<YOUR-API-KEY>",
  authDomain: "<APP-NAME>.firebaseio.com",
  storageBucket: "<APP-NAME>.appspot.com",
}
firebase.initializeApp(config)

6. Enable Blob and XMLHttpRequest polyfills:

const Blob = RNFetchBlob.polyfill.Blob
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob

7. Implement uploadImage function:

const uploadImage = (uri, mime = 'application/octet-stream') => {
  return new Promise((resolve, reject) => {
    const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri
      const sessionId = new Date().getTime()
      let uploadBlob = null
      const imageRef = storage.ref('images').child(`${sessionId}`)

      fs.readFile(uploadUri, 'base64')
      .then((data) => {
        return Blob.build(data, { type: `${mime};BASE64` })
      })
      .then((blob) => {
        uploadBlob = blob
        return imageRef.put(blob, { contentType: mime })
      })
      .then(() => {
        uploadBlob.close()
        return imageRef.getDownloadURL()
      })
      .then((url) => {
        resolve(url)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

Basically it uses Firebase SDK to create a reference to the Storage folder, then writes the binary data from the selected image to it.

For Blob type, I find it most stable to encode the binary data with Base64 first. I hope it will get more stable in future release of react-native-fetch-blob

The demo app is available at this public github repo:

Firebase-Image-Upload-React-Native

Feel free to download and modify it for your project. Happy image uploading!

Thien is a full-stack engineer with 5 years experience developing mobile and web products ranging from action titles enjoyed by gamers in Japan, education apps used by students and teachers in Vietnam, and human resource management apps used by managers and employees in North America.
You might also like...
To stay productive in programming you need to receive feedback for your code as fast as possible. For example, when you want to test out some styling effects with CSS...
Basically it's where you deploy your code to. Using a PaaS has several benefits over Infrastructure-as-a-Service (IaaS) or setting your own physical servers...
React Native provides its own version of ListView, it is essentially different from Android's ListView or iOS'es UITableView...
contact codelink

Contact

Let us know how we can help!