2

我在查看已上传到 firebase 的图像文件时遇到问题,只是注意到问题出在 firebase 中的文件类型上。

在此处输入图像描述

我的 Firebase 存储控制台中有两个文件。一个从我的 IOS 模拟器(八位字节流)上传,另一个从浏览器直接上传到控制台,该浏览器可以正确上传并且可以查看。

这是我的选择和上传功能:

_selectPhoto = async () => {

    const status = await getPermission(Permissions.CAMERA_ROLL);
    if (status) {
      let imageName = "pic"
      const result = await ImagePicker.launchImageLibraryAsync(options);
      if (!result.cancelled) {
        Animated.timing(this.animatedWidth, {
          toValue: 600,
          duration: 15000
      }).start()
        this.uploadImage(result.uri, imageName)
        .then(() => {
        this.props.navigation.navigate('Profile')
        })        
        .catch((error) => {
          Alert.alert('Must Sign In');
          this.props.navigation.navigate('Login')
          console.log(error);

        })
      }
    }


  };


uploadImage = async (uri, imageName) => {

    const user = firebase.auth().currentUser;
    const response = await fetch(uri);
    const blob = await response.blob();
    let storageRef = firebase.storage().ref().child(''images/'+user.displayName+'/'+imageName+'.jpg'');

    const snapshot = await storageRef.put(blob);
    blob.close();
    snapshot.ref.getDownloadURL().then(function(downloadURL) {
      console.log("File available at", downloadURL);
      user.updateProfile({
        photoURL: downloadURL.toString(),
        }).then(function() {
            console.log('saved photo')

        }).catch(function(error) {
            console.log('failed photo')

        });

    });

}

当我在控制台中获得链接时,它也有媒体和令牌:

... .appspot.com/o/profile-pic.jpg?alt=media&token=56eb9c36-b5cd-4dbb-bec1-3ea5c3a74bdd

如果我在 VS Code 中 CMD+单击,我会收到一个错误:

{
  error: {
    code: 400,
    message: "Invalid HTTP method/URL pair."
  }
}

所以很自然,当我将该链接放入浏览器时,它会下载一个具有该名称的文件,但会显示:

无法打开文件“pic.jpg”。它可能已损坏或使用了 Preview 无法识别的文件格式。

也许它可能与 mediaTypes 有关,但我不确定如何使用它。

mediaTypes : String -- 选择要选择的媒体类型。用法:ImagePicker.MediaTypeOptions.,其中之一是:图像、视频、全部。

谢谢!

4

1 回答 1

4

在过去的几天里,我一直在与同样的问题作斗争。通过遵循Expo repo 中的 Firebase Upload 示例,我终于能够按预期上传和呈现图像。我不完全理解它为什么起作用,但似乎 Firebase 不喜欢由

const blob = await response.blob();

尝试将上述内容替换为:

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);
  });
于 2019-03-07T02:29:20.500 回答