Firebase 云存储加载预览上传图片时出错

Firebase Cloud Storage Error Loading Preview Uploaded Image

我使用 react-native-image-picker 的 base64 生成数据上传了一张图片。它在 Firebase 控制台上显示正常,但是当我尝试在我的浏览器上查看它时,它显示“错误加载预览”,当我点击它时,它只是一个黑框。请参阅下面的屏幕截图

这是我的上传代码:

const uploadImage = async ({data, filename, uri}) => {
    const ext = uri.split('.').pop();
    const name = uri.split('/').pop();
    const path = `${user.uid}_${name}`;
    const storageRef = firebase.storage().ref(`profiles/${path}`);
    storageRef
        .putString(data, 'base64', {contentType: `image/${ext}`})
        .then(function (snapshot) {
            console.log('SUCCESSSSS');
        });
};
    useEffect(() => {
        ImagePicker.showImagePicker((response) => {
            //console.log('Response = ', response);

            if (response.didCancel) {
                console.log('User cancelled image picker');
            } else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
            } else if (response.customButton) {
                console.log('User tapped custom button: ', response.customButton);
            } else {
                console.log(response.uri);
                uploadImage(response);

                setAvatar({uri: response.uri});
            }
        });
    }, []);

编辑:我将 base64 字符串复制到在线转换器中,看起来不错,它返回了正确的图像。所以数据没有任何问题,它看起来像。 firebase 处理它的方式有问题。

编辑:我尝试将类型明确设置为 image/jpeg 而不是 image/jpg,如此处所述:Proper way to show image when Firestorage is down or Error loading preview in Firestorage for iOS 但没有区别。

看起来 firebase 的 base64 putString 方法和 react-native 涉及的错误不止几个:请参阅此线程:https://github.com/firebase/firebase-js-sdk/issues/576。我听从了 yonahforst 的回答,最后改用了 blob。完美运行。

复制在这里以防线程消失:

function urlToBlob(url) {
  return new Promise((resolve, reject) => {
      var xhr = new XMLHttpRequest();
      xhr.onerror = reject;
      xhr.onreadystatechange = () => {
          if (xhr.readyState === 4) {
              resolve(xhr.response);
          }
      };
      xhr.open('GET', url);
      xhr.responseType = 'blob'; // convert type
      xhr.send();
  })
}

确保添加“data:image/jpeg;base64,9asdf92349...”(如果不存在)。我使用的是 react-native-image-picker,所以它没有开箱即用。

const dataURL = 'data:image/jpeg;base64,' + data;
    urlToBlob(dataURL).then((blob) => {
        storageRef
            .put(blob)
            .then(function (snapshot) {
                const downloadURL = snapshot.ref.getDownloadURL().then((link) => {
                    console.log('link: ', link);
                    user.updateProfile({photoURL: link});
                });
            })
            .then(() => console.log('SUCCESS'));
    });