@ react-native-firebase / storage-上传图像后获取网址

时间:2019-12-30 03:10:46

标签: react-native firebase-storage react-native-firebase

我正在尝试找到一种有效的方法,以便在ive上传后立即在firebase中获取图像的网址。 我想避免为此编写一个完全独立的函数。而是希望将其包括在Promise链中。参见下面的代码

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

3 个答案:

答案 0 :(得分:0)

您可以使用await创建承诺链,然后轻松获取您的下载网址,如下所示:

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

答案 1 :(得分:0)

基尚(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);
    }
  };

答案 2 :(得分:0)

就我而言,uri使用Android权限抛出了一个错误。因此,以下功能对我有用。代替uri,我从ImagePicker传递了res​​ponse.path。提示:您可以使用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);
    }
};