javascript - 使用 React-Native 将图像上传到 Firebase

标签 javascript firebase react-native

我正在使用这种方法尝试通过我的 React-Native 应用程序将图像上传到 Firebase,因为它似乎是互联网上非常常见的示例,但是我认为它已经很老了,我怀疑它不再适用于较新版本的 React-Native。

谁能告诉我在 Firebase 存储中保存图像的正确方法,谢谢!

 const uploadImage = (uri, imageName, mime = 'image/jpg') => { 

    return new Promise((resolve, reject) => {
      const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') 
  : uri;
      let uploadBlob = null
      const imageRef = firebase.storage().ref('images/').child(imageName)
      fs.readFile(uploadUri, 'base64')
        .then((data) => {
          return Blob.build(data, {type: `${mime};BASE64`})
        })
        .then((blob) => {
          uploadBlob = blob
          return imageRef.put(blob, {contentType: mime})
        })
        .then(() => {
          uploadBlob.close()
          return imageRef.getDownloadURL()
        })
        .then((url) => {
          resolve(url)
        })
        .catch((error) =>{reject(error)})
    })
}

最佳答案

您可以只使用 putFile 方法。

这是我的带有 saveImage 方法的 FirebaseStorageService(我使用的是 RN 0.53 和 react-native-firebase 4.1.0):

saveImage(ref, image, imageName, onSuccess, onError){
    LOG.debug("FirebaseStorageService :: saveImage ", {ref:ref, image:image, imageName:imageName});

    var firebaseStorageRef = firebase.storage().ref(ref);
    const imageRef = firebaseStorageRef.child(imageName + ".jpeg");

    LOG.debug("FirebaseStorageService :: imageRef ", {imageRef:imageRef});


    imageRef.putFile(image.path, {contentType: 'image/jpeg'}).then(function(){
        return imageRef.getDownloadURL();
    }).then(function(url){
        LOG.debug("Image url", {url:url});
        onSuccess(url);
    }).catch(function(error){
        LOG.error("Error while saving the image.. ", error);
        onError(error);
    });
}

图片是react-native-image-crop-picker返回的图片.用户可以在打开相机和打开图库之间进行选择,并返回一个图像对象。

图像对象的路径属性只是一个字符串,如 Android 的“file://..”和 iOS 的“/Users/...”。

关于javascript - 使用 React-Native 将图像上传到 Firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50728362/

相关文章:

java - 无法使用 picasso 从 firebase 检索图像

javascript - 在 React Native 中测试原生事件发射器和原生模块

android - react 导航动画切换页面过渡

javascript - 标记不显示在 map api V3 中

javascript - .prev() 方法不起作用

cordova - 如何将 Google 标签管理器 + Firebase 集成到 cordova 应用程序中?

javascript - 使用 Firebase 的 Angular 2 应用程序的性能

android - 生产包 React Native 上的 "Unhandled JS Exception: t is not a function. (In ' t(c) ', ' t ' is false)"

javascript - 将 JavaScript 添加到我的轮播

javascript - 亚马逊支付与 Javascript 和 PHP 的集成 - PaymentPlanNotSet