how to save an image to firebase storage?

Viewed 50

I have a function that allows me to select an image from the gallery or take a photo using the camera.

import React, {useState} from 'react';
import {View, TouchableOpacity, Text, StyleSheet, Image} from 'react-native';

import ImagePicker from 'react-native-image-picker';

export default function Upload() {
  const [avatar, setAvatar] = useState();

  function imagePickerCallback(data) {
    if (data.didCancel) {
      return;
    }

    if (data.error) {
      return;
    }

    if (data.customButton) {
      return;
    }

    if (!data.assets[0].uri) {
      return;
    }

    setAvatar(data.assets[0]);
  }

  return (
    <View style={styles.container}>
      <Image
        source={{
          uri: avatar
            ? avatar.uri
            : 'https://mltmpgeox6sf.i.optimole.com/w:761/h:720/q:auto/https://redbanksmilesnj.com/wp-content/uploads/2015/11/man-avatar-placeholder.png',
        }}
        style={styles.avatar}
      />
      <TouchableOpacity
        style={styles.button}
        onPress={() =>
          ImagePicker.launchCamera(imagePickerCallback)
        }>
        <Text style={styles.buttonText}>camera</Text>
      </TouchableOpacity>

      <TouchableOpacity
        style={styles.button}
        onPress={() =>
          ImagePicker.launchImageLibrary(imagePickerCallback)
        }>
        <Text style={styles.buttonText}>galery</Text>
      </TouchableOpacity>

    </View>
  );
}

This function is working correctly, my only question is how to get this image that is being recorded inside the state avatar and save it in firebase storage generating a URL for this image?

1 Answers

In order to upload an image to firebase you will first have to set it up, you can read the detailed explanation on how to achieve that here -> https://rnfirebase.io/

Next, you will have to install the storage module, which will allow you to upload your files to firebase https://rnfirebase.io/storage/usage

Once everything is set up you can use the firebase.storage() directive to upload your assets.

Before the actual upload you will need to create a reference for it. A reference is a local pointer to some file on your bucket. This can either be a file that already exists or one which does not exist yet. To create a reference, use the ref method: firebase.storage().ref(path-where-you-want-to-save-your-file)

After the upload is complete you can use the getDownloadURL() function to actually get the URL you're going to use

Now you can finally upload your file using the putFile method. Here is an example of a helper function you could use:

import firebase from '@react-native-firebase/app'

async function uploadImage(url) {   
  const storageRef = firebase.storage().ref(`path-where-you-want-to-save/${url}`)
  await storageRef.putFile(url)
  const url = await storageRef.getDownloadURL()
  return url
}
Related