Home > database >  Uploading image onto firebase storage and retrieve it as user profile picture
Uploading image onto firebase storage and retrieve it as user profile picture

Time:07-07

Using React Native with Expo CLI and Firebase. I am creating a profile screen using react native image picker and I want to upload the image chosen using image picker onto the firebase cloud. But I have no idea how to do so. Please help! Below is a code snippet:

import React, { useState, useEffect } from 'react';
import { Button, Image, View, Platform } from 'react-native';
import * as ImagePicker from 'expo-image-picker';

import {getStorage, ref, uploadBytes} from '@react-native-firebase/storage'

export default function ImagePickerExample() {
  const [image, setImage] = useState(null);

  const pickImage = async () => {
    // No permissions request is necessary for launching the image library
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    console.log(result);

    if (!result.cancelled) {
      setImage(result.uri);
    }
  };

  const storage = getStorage();
  const filename = "test.jpg"
  const storageRef = ref(storage, filename);

  uploadBytes(storageRef, file).then((snapshot) => {
    console.log('Uploaded a blob or file!');
  });

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button title="Pick an image from camera roll" onPress={pickImage} />
      {image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
    </View>
  );
}

Not only do I want to upload images to firebase, I also want to retrieve this image and display as the user profile picture. If possible, please guide me through the whole process with code snippets!

CodePudding user response:

You'll first want to retrieve the chosen image object's URI value, then upload this URI to firebase storage. You must trim the URI string because iOS adds a 'file://' prefix to image URI's, which we don't need.

function revealImagePicker() {
    ImagePicker.launchImageLibrary(options, (response) => {
        const uri = response.uri;
        let uploadUri =
          Platform.OS === 'ios' ? uri.replace('file://', '') : uri;
          firebase
            .storage()
            .ref(user.uid)
            .putFile(uploadUri)
            .catch((error) => {
              alert(error);
            });
        });
}

You can use the unique auto-generated firebase uid to save the image in firebase storage. This ensures that when you want to download a user's profile image, you can just search in storage for their uid. When you want to retrieve an image from firebase storage, you just need to download the ref from firebase storage like so:

firebase
      .storage()
      .ref(user.uid)
      .getDownloadURL()
      .then((result) => {
        if (result != null) {
          //Do whatever you want to with the image
        }
      })

To display the associated image from the retrieve URI, react native allows you to create an Image component with URI as its source like so:

<Image source={{uri: retrievedURI}}/>
  • Related