Search code examples
mongodbreact-nativefeathersjs

I want to upload an image from react-native to mongoDB using feathersJS


i am using feathersJS to work with a project of an e-commerce application on react-native i am unable to upload an image into the database, i am also creating a blob file with react-native-blob but it isn't working, its throwing an error of FileReader.readAsArrayBuffer is not implemented. I just want to upload an image and then get it back please help me with the react-native.

https://github.com/feathersjs/feathers/issues/348

uploadImageFromDevice = () => {
    const options = {
      title: 'Select a Photo',
      cancelButtonTitle: 'Cancel',
      takePhotoButtonTitle: 'Take Photo…',
      chooseFromLibraryButtonTitle: 'Choose from Library…'
    };
    ImagePicker.showImagePicker(options, (response) => {
      console.log('Response = ', response);
      if (response.didCancel) {
        console.log('User cancelled image picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
      } else {
        { this.storeImageToFeathers(response, response.fileName); }
      }
    });
  }

storeImageToFeathers = (response, mime = ';BASE64') => new Promise((resolve, reject) => {
    const uri = response.uri;
    const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri;
    const name = new Date().toString();
    const imageRef = firebase.storage().ref('/photos/posts').child(name);
    fs.readFile(uploadUri, 'base64')
      .then(data => Blob.build(data, { type: `${mime};BASE64` }))
      .then((blob) => {
        console.log(blob);
        client.service('image-upload').create({
          uri: blob
        }).then((res) => console.log(res))
          .catch(err => console.log(err.message))
       })
  })


Solution

  • In order to upload a file to feathersjs you should use a multipart form. You have to install the module multer that uses Express middleware to get the uploaded file.

    This this is a nice article for doing that.

    The problem with your approach is that you are uploading the file in string64 format. That has the big problem that when the file is a little big, the request can fail because of the size. The multipart form uploads the file in batches.