Home > Back-end >  How to make firebase image path work as an image on different devices on React Native?
How to make firebase image path work as an image on different devices on React Native?

Time:10-10

I have a function that requests the user for an image from their phone. Once this is given, the path is uploaded to firebase and looks something like this:

file:///var/mobile/Containers/Data/Application/9C627709-0F0C-4A2A-939E-9206DA91032C/Library/Caches/ExponentExperienceData/%40user%2FAPP/ImagePicker/1B5D0907-8ED5-46DC-B216-7DEF7992C1BF.jpg"

The problem is that on the attempt to display it only displays on the phone that this image has been uploaded on, since other devices do not possess this image.

How can I convert the firebase path/image into an image that is displayable in all phones, even though this image does not exist on all users devices?

Here is some important bits of code:

function that gets the library image

const addImage = async () => {
    let image = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });
    if (!image.cancelled) {
      setGalleryImage(image.uri);
    }
  };

function that adds the image to firebase:

  const createPhoto = async () => {
    await db
      .collection("data")
      .doc(route?.params?.docId)
      .set(
        {
          galleryImage,
        }
      )
      .then(() => {
      })
      .catch(error => alert(error));
  };

Jsx that displays the image:

<Image
     source={{ uri: galleryImage }}
     onl oadStart={() => setIsLoading(true)}
     onl oadEnd={() => setIsLoading(false)}
  />

Any help is appreciated

CodePudding user response:

This is because, you are saving the local path of the image, hence it can not be displayed on other phones. You need to upload the image to a storage bucket and save the URL of that image on the db.

Convert image to blob

const blob = await new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function() {
        resolve(xhr.response);
    };
    xhr.onerror = function() {
        reject(new TypeError("Network request failed"));
    };
    xhr.responseType = "blob";
    // image.uri is the local path of the image on the device
    xhr.open("GET", image.uri, true);
    xhr.send(null);
})

Upload image to storage

const storageRef = ref(storage, `profile-pictures/${userContext.user.uid}/${name}`);
const task = uploadBytesResumable(storageRef, blob)
task.on('state_changed', (snapshot) => {
    const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
}, (err) => {
    reject(err)
}, () => {
    getDownloadURL(task.snapshot.ref)
    .then((downloadURL) => {
        // image successfully uploaded, save "downloadURL" in your db
    })
})
  • Related