vale1234ntina123
vale1234ntina123

Reputation: 85

Try to upload an image into firebase storage

i'm trying to upload and image from a device to firebase storage but i don't know which format i should use. i've try with put and putString, but both of them gave me invalid argument.

This is the code to pick and upload the image.

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

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

  const uploadImage = async () => {
    if (!image) {
      Alert.alert(
        'You have to choose an image first'
      );
    } else {
      const uri = image;
      console.log(uri);
      const filename = uri.substring(uri.lastIndexOf('/') + 1);
      const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri;
      setUploading(true);
      setTransferred(0);
      const task = firebase.storage()
        .ref(filename)
        .put(uploadUri);
      // set progress state
      task.on('state_changed', snapshot => {
        setTransferred(
          Math.round(snapshot.bytesTransferred / snapshot.totalBytes) * 10000
        );
      });
      try {
        await task;
      } catch (e) {
        console.error(e);
      }
      setUploading(false);
      Alert.alert(
        'Photo uploaded!',
        'Your photo has been uploaded to Firebase Cloud Storage!'
      );
      setImage(null);
      }
};

This is the uri of the image (the console.log output) : enter image description here

This is the error using .put(uploadUri):

enter image description here

This is the error using .putString(uploadUri, 'data_url') :

enter image description here

Upvotes: 0

Views: 430

Answers (1)

Marco Caldera
Marco Caldera

Reputation: 505

In order to upload an image on Firebase storage using put you need to pass a blob as param instead of string.

For example you can do something like this:

import path from 'path'

const uid = 'image-id'
const fileName = uid + path.extname(uri)
const response = await fetch(uri)
const blob = await response.blob()


const uploadImage = firebase
      .storage()
      .ref()
      .put(blob, {
        contentType: `image/${path.extname(uri).split('.').pop()}`
      })

uploadImage.on(
      'state_changed',
      snapshot => {
        // progress
      },
      err => {
        // error
      },
      () => {
        // complete
      }

Upvotes: 2

Related Questions