首页 > 解决方案 > 如何使用expo将图像上传到firebase?

问题描述

这是我从 github expo 示例https://github.com/expo/examples/tree/master/with-firebase-storage-upload中获取的代码,用于将图像上传到 Firebase 存储。

 const pickImage = async () => {
        let pickerResult = await ImagePicker.launchImageLibraryAsync({
          allowsEditing: true,
          aspect: [4, 3],
        });
    
            handleImagePicked(pickerResult);
      };
      

      const handleImagePicked = async (pickerResult) => {
        try {
          
    
          if (!pickerResult.cancelled) {
             await uploadImageAsync(pickerResult.uri);
             console.log('done')
          }
        } catch (e) {
          console.log(e);
          alert('Upload failed, sorry :(');
        } finally {
        }
      };
    
      async function uploadImageAsync(uri) {
        // Why are we using XMLHttpRequest? See:
        // https://github.com/expo/expo/issues/2402#issuecomment-443726662
        const blob = await new Promise((resolve, reject) => {
          const xhr = new XMLHttpRequest();
          xhr.onload = function() {
            resolve(xhr.response);
          };
          xhr.onerror = function(e) {
            console.log(e);
            reject(new TypeError('Network request failed'));
          };
          xhr.responseType = 'blob';
          xhr.open('GET', uri, true);
          xhr.send(null);
        });
      
        const ref = firebase
          .storage()
          .ref()
          .child("images"+Math.random());
        const snapshot = await ref.put(blob);
      
        // We're done with the blob, close and release it
        blob.close();
      
        return await snapshot.ref.getDownloadURL();
      }

它在 Android 上运行良好,但在 ios 上它给出错误消息 Event {isTrusted: false},网络请求失败。先感谢您

标签: firebasereact-nativeexpoimage-upload

解决方案


这是 react-native 的回归,它在最近的补丁版本中得到了修复:https ://github.com/expo/expo/issues/10464#issuecomment-703178030

得到修复:

  • 从商店下载最新的 iOS 和 Android 客户端。
  • 使用 expo client:install:ios 和 expo client:install:android 安装最新的 iOS 和 Android 客户端

推荐阅读