Arthur Prasniski
Arthur Prasniski

Reputation: 75

Upload image in firebase expo react native

i have an issue, i trying solve a several hours but white not success, my issue consists in create an upload to firestorage in firebase and show your respective uri in a variable i called image, but i don't know what wrong in my code, why he save my image like this saved image

and don't show you uri in my variable

bellow is my code

This is a create user i set here in imageUri a uploadImage who i called in my variable image

const createUser = async () => {
    const imageUri = uploadImage()
    await addDoc(
      usersCollectionRef,
      {
        name: name || null,
        cep: cep || null,
        logradouro: logradouro || null,
        numero: numero || null,
        bairro: bairro || null,
        uf: uf || null,
        image: imageUri || null,
      },      
      navigation.navigate("HomeScreen")
    );
  };

here is a code i pick image and my upload function to set a image in firestore (i follow the docs)

   const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });
    console.log(result);
    if (!result.cancelled) {
      setImage(result);
    }
  };

  const uploadImage = () => {
    const storageRef = ref(storage, `images/${image.name}`);
    uploadBytes(storageRef, image).then((snapshot) => {
      console.log(snapshot);
    });
  };

i really need some help for solve this issue i appreciate every tryed of help, any more questions about my code please comment if need i send my repository.

Upvotes: 0

Views: 1509

Answers (1)

Mauro Russo
Mauro Russo

Reputation: 357

There are some mistakes in your code.

First, the ImagePicker returns an object like that (docs) :

{
  "cancelled":false,
  "height":1611,
  "width":2148,
"uri":"file:///data/user/0/host.exp.exponent/cache/cropped1814158652.jpg"
}

There is no "name" field, that's why you see that undefined, because you access ${image.name}.

Second, as far as ImagePicker returns an object, you can't use it on uploadBytes pretending it is a Blob or similar. You should create a Blob from the uri image:

const response = await fetch(imageUri)
const blobFile = await response.blob()

Definetely, this is a function I suggest you to use for uploading an image on firebase storage

export async function uploadImage(imageUri) {
  try {
    const response = await fetch(imageUri)
    const blobFile = await response.blob()

    const reference = ref(storage, "your_name.jpg")
    const result = await uploadBytes(reference, blobFile)
    const url = await getDownloadURL(result.ref)

    return url
  } catch (err) {
    return Promise.reject(err)
}

}

Upvotes: 1

Related Questions