james murphy
james murphy

Reputation: 1785

@react-native-firebase/storage - get url after uploading an image

Im trying to find an efficient way to get the url of an image in firebase right after ive uploaded it. Id like to avoid writing a totally separate function to this....and instead Id like to include it in the promise chain. See code below

import storage from '@react-native-firebase/storage';

storage()
        .ref('path/to/remote/folder')
        .putFile('uri/of/local/image')
        .then(() => {
          //Id like to use getDownloadUrl() function here;
        })

Upvotes: 4

Views: 6770

Answers (3)

Sudaraka Senevirathne
Sudaraka Senevirathne

Reputation: 377

In my case, uri threw an error with Android permissions. So following function worked for me. Instead of uri, I passed response.path from the ImagePicker. Tip: you can use uuid to generate random file name.

this.uploadAndReturnFirestoreLink(response.path, 'images/' + 'example.jpg')

uploadAndReturnFirestoreLink = async (loaclPath, folderPath) => {
    console.log(loaclPath)

    try {
        const imageRef = storage().ref(folderPath);
        await imageRef.putFile(loaclPath, { contentType: 'image/jpg' });
        const url = await imageRef.getDownloadURL();
        console.log(url)
        alert('Upload Success', url)
    } catch (e) {
        console.log(e);
    }
};

Upvotes: 0

james murphy
james murphy

Reputation: 1785

Good answer from Kishan but did not work for me....below includes some minor modifications so would work for me.

const localUri = Platform.OS === 'ios' ? imgPickResponse.uri.replace('file://', '') : imgPickResponse.uri;

          this.uploadImageAndGetUrl(localUri, '/profilePics/' + this.props.userId)
          .then(url => {console.log(url);}); 
}


  uploadImageAndGetUrl = async (localUri, firebasePath) => {
    try {
      const imageRef = storage().ref(firebasePath);
      await imageRef.putFile(localUri, {contentType: 'image/jpg'});
      const url = await imageRef.getDownloadURL();
      return url;
    } catch (err) {
      Alert.alert(err);
    }
  };

Upvotes: 0

Kishan Bharda
Kishan Bharda

Reputation: 5690

You can create chain of promises using await and then easily get your download url as below :

/**
 * Upload the image to the specific firebase path
 * @param {String} uri Uri of the image
 * @param {String} name Name of the image
 * @param {String} firebasePath Firebase image path to store
 */
const uploadImage = async (uri, name, firebasePath) => {
  const imageRef = storage().ref(`${firebasePath}/${name}`)
  await imageRef.putFile(uri, { contentType: 'image/jpg'}).catch((error) => { throw error })
  const url = await imageRef.getDownloadURL().catch((error) => { throw error });
  return url
}

Now you can call this function as below :

const uploadedUrl = await uploadImage('uri/of/local/image', 'imageName.jpg', 'path/to/remote/folder');

Now uploadedUrl will contains url of the uploaded image.

Upvotes: 6

Related Questions