React Native 如何修复照片上传错误到firebase存储

rpppsulh  于 2023-04-12  发布在  React
关注(0)|答案(1)|浏览(179)

对于我的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();
}
xpcnnkqh

xpcnnkqh1#

我的更新代码

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

相关问题