繁体   English   中英

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM