Upload Image from React Native to MongoDB Atlas using Nodejs Express Multer

Viewed 1034

I am trying to upload a profile image of a user from React Native App(Android). I am new to uploading image so I searched and found a package called multer. As I am using Mongodb Atlas, multer has a storage option of MemoryStorage and using MemoryStorage I tried uploading the image to Atlas.But the problem I am facing is that I dont the format in which I have to send the data to Nodejs. I use FormData() to send the image details to Nodejs.I may be wrong in choosing the format or package or anywhere.Please correct me if find me wrong anywhere.Below is code for everything.

avatar.js

const avatarSchema = new Schema(
  {
    profile_avatar: {
      type: Buffer,
      contentType: String,
      //   required: [true, 'fee is required'],
    },
  },
  {
    timestamps: true,
  },
);
const avatar = mongoose.model('avatar', avatarSchema);

module.exports = avatar;

avatar route

let Avatar = require('../models/avatar');
const multer = require('multer');
var storage = multer.memoryStorage();
var upload = multer({storage: storage});

router.route('/add/image').post(upload.single('avatar'), (req, res, next) => {
  console.log(req); // it does not get hit  
  var newAvatar = new Avatar();
  newAvatar.profile_avatar = req.file.buffer;
  newAvatar.save(function(err) {
    console.log('error', err);
    if (err) {
      console.log(error);
    } else {
      res.send({message: 'uploaded successfully'});
    }
  });
});

React Native Code


//Function to select single image from gallery(its working fine)
imagePick = () => {
    let options = {
      quality: 0.2,
      maxWidth: 500,
      maxHeight: 500,
      allowsEditing: true,
      noData: true,
      storageOptions: {
        skipBackup: false,
        path: 'images',
      },
    };
    ImagePicker.launchImageLibrary(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);
        alert(response.customButton);
      } else {
        this.setState({
          imageData: response,
        });
      }
    });
  };

//Function to structure FormData

 createFormData = photo => {
    const data = new FormData();
    data.append('avatar', {
      name: photo.fileName,
      type: photo.type,
      uri:
        Platform.OS === 'android'
          ? photo.uri
          : photo.uri.replace('file://', ''),
    };);
    return data;
  };

//Function to send Image data to Nodejs(Not Working)
 sendImage = () => {
     fetch('http://10.0.2.2:5000/user/add/image', {
       method: 'POST',
       credentials: 'same-origin',
       redirect: 'follow',
       referrer: 'no-referrer',
       body: this.createFormData(this.state.imageData),
     })
       .then(response => response.json())
       .then(response => {
         console.log('upload succes', response);
         Alert.alert('Upload success!');
       })
       .catch(error => {
         console.log('upload error', error);
         Alert.alert('Upload failed!');
       });
  };

Any other way I can upload the image? Any help would be appreciated.

0 Answers
Related