在React Native存储中上传图像时缺少参数'path'

时间:2019-03-18 18:55:49

标签: reactjs firebase react-native native firebase-storage

我正在尝试允许用户将图像上传到Firebase实时数据库。 我同时使用了“ rn-fetch-blob”和“ react-native-fetch-blob”,但无法正常工作。

通过此功能选择照片,将照片保存为头像状态。

selectPhoto() {
    const options = {
      quality: 1.0,
      maxWidth: 500,
      maxHeight: 500,
      storageOptions: {
        skipBackup: true
      }
    };
    ImagePicker.showImagePicker(options, (response) => {
      if (response.didCancel) {
        console.log('User cancelled photo picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
      } else {
        let source = { uri: response.uri };
        this.setState({ avatar: source });
      }
    })
  }

然后,uploadPhoto尝试将其上传到Firebase,但在“ RNFetchBlob.fs.readFile”行上出现“缺少参数'path'”错误

uploadPhoto(mime = 'application/octet-stream') {
    return new Promise((resolve, reject) => {
      const uploadUri = this.state.avatar;
      let uploadBlob = null
      console.log('uid' + this.state.uid);
      const imageRef = firebase.storage().ref('applicants' + this.state.uid).child('profile_pic');

      console.log(this.state.avatar);
      RNFetchBlob.fs.readFile(this.state.avatar, 'base64')
        .then((data) => {
          return Blob.build(data, { type: `${mime};BASE64` })
        })
        .then((blob) => {
          uploadBlob = blob
          return imageRef.put(blob_ref, blob, { contentType: mime })
        })
        .then(() => {
          uploadBlob.close()
          return imageRef.getDownloadURL()
        })
        .then((url) => {
          resolve(url)
        })
        .catch((error) => {
          alert(error.message);
          reject(error);
      })
    })
  }

1 个答案:

答案 0 :(得分:0)

使用rn-fetch-blob,因为不再维护react-native-fetch-blob。通过查看您的代码,我的猜测是您未指定文件名,而文件名将是路径。这是我如何从保存到文件系统中的png创建FormData / Blob的示例:

imageToFormData(filename: string): FormData {
    const data = new FormData();
    data.append('file', { uri: `file://${directory}/${filename}`, name: filename, type: 'image/png' });

    return data;
  }

因此,请在您的代码中尝试按上述或以下步骤构建blob:

.then((data) => {
          return Blob.build(data, { name: ${filename}, type: `${mime};BASE64` })
        })