如何修复照片上传错误到Firebase存储

时间:2019-01-28 18:12:21

标签: firebase react-native upload expo

对于我的react-native(我正在使用EXPO)应用程序,我希望用户上传个人资料图片,该图片将存储在firebase存储中。为此,我使用了this example code并对其进行了修改。但是,除非我处于调试模式,否则此示例对我不起作用。

我可以打开ImagePicker,然后编辑照片,但是上传失败。

我发布了代码快照。通过单击按钮,将调用_pickImage()

此问题可能是什么原因?我的建议是,在调试模式下,该应用程序有更多时间来处理该功能,因为在调试模式下,该应用程序确实很落后。

我是react-native的新手(通常是应用程序开发人员),对此我深表歉意!

非常感谢您。

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

    this._handleImagePicked(pickerResult);
  };

  _handleImagePicked = async pickerResult => {
    try {
      this.setState({ uploading: true });

      if (!pickerResult.cancelled) {
        uploadUrl = await uploadImageAsync(pickerResult.uri);
        this.setState({ image: uploadUrl });
      }
    } catch (e) {
      console.log(e);
      alert('Upload failed, sorry :(');
    } finally {
      this.setState({ uploading: false });
    }
  };
}

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(uuid.v4());
  const snapshot = await ref.put(blob);

  // We're done with the blob, close and release it
  blob.close();

  return await snapshot.ref.getDownloadURL();
}

1 个答案:

答案 0 :(得分:0)

我的更新代码

import { ImagePicker } from 'expo';
import { RNS3 } from 'react-native-aws3';
YellowBox.ignoreWarnings(['Setting a timer']);
var _ = require('lodash');
    .
    .
    .
componentDidMount(){
      this.firebaseRef = firebase.database().ref('newsfeed')
      this.firebaseRef.on('value', snap => {
        const newsfeed = snap.val()
        const newNewsfeed = _.reverse(_.values(newsfeed));
        this.setState({ postList: newNewsfeed, loadingPost: false })
      })
  }
  async onAddPhoto(){
    let result = await ImagePicker.launchImageLibraryAsync({
     allowsEditing: true,
     aspect: [4, 3],
   });

   if (!result.cancelled) {
     this.setState({ photo: result.uri });
     options["contentType"] = result.type

   }

  }
  onPressPost(){
    this.setState({ loading: true})
    const _this = this
    let post = {}
    post["id"] = firebase.database.ServerValue.TIMESTAMP
    post["text"] = this.state.text
    if(this.state.photo){
      const uri = this.state.photo
      const ext = uri.substr(uri.lastIndexOf('.') + 1);
      const name = Math.round(+new Date()/1000);
      let file = {
        name: name+"."+ext,
        type: "image/"+ext,
        uri
      }

      RNS3.put(file, options).then(response => {
          if(response.status === 201){
            post["photo"] = response.body.postResponse.location
            firebase.database().ref('newsfeed').push(post)
            _this.setState({ text: '', photo: null, loading: false})
          }
      });

    }else {
      firebase.database().ref('newsfeed').push(post)
      _this.setState({ text: '', photo: null, loading: false})
    }

  }