@react-native-firebase/storage - 上传图片后得到url

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

我试图找到一种有效的方法来在我上传图像后立即在 firebase 中获取图像的 url。 我想避免为此编写一个完全独立的函数……而是我想将它包含在承诺链中。请参阅下面的代码

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;
        })

您可以使用 await 创建承诺链,然后轻松下载 url,如下所示:

/**
 * 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
}

现在你可以调用这个函数如下:

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

现在 uploadedUrl 将包含 url 上传的图片。

Kishan 的回答很好,但对我不起作用....下面包括一些小的修改,所以对我有用。

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);
    }
  };

在我的例子中,uri 抛出了 Android 权限错误。所以以下功能对我有用。我从 ImagePicker 传递了 response.path 而不是 uri。提示:可以使用uuid生成随机文件名。

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);
    }
};