1
votes

I am trying to allow the user to upload an image to Firebase Real-time database. I have used both 'rn-fetch-blob' and 'react-native-fetch-blob', but couldn't get it to work.

The photo is selected through this function which saves it to the avatar state.

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

The uploadPhoto then tries to upload it to Firebase but I am getting a "missing argument 'path'" error on the line 'RNFetchBlob.fs.readFile'

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
What is the exact contents of this.state.avatar at the time of the call? - Doug Stevenson
@DougStevenson it shows up like file:///storage/emulated/0/Android/data/com.jobsearch/files/Pictures/image-e4d88136-ac45-4f5b-81e3-f0d394343e59.jpg - angielle
Is that a valid path for readFile? - Doug Stevenson

1 Answers

0
votes

Use rn-fetch-blob as react-native-fetch-blob is no longer maintained. My guess from looking at your code is that you are not specifying a filename, which would be the path. Here is an example of how I am creating my FormData/Blob from a png saved to the filesystem:

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

    return data;
  }

So in your code try building your blob as above or the following:

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