使用Nodejs Express Multer将图像从React Native上传到MongoDB Atlas

时间:2020-05-08 23:38:16

标签: javascript node.js react-native multer mongodb-atlas

我正在尝试从React Native App(Android)上传用户的个人资料图片。我是上传图片的新手,所以我搜索了一个名为multer的软件包。当我使用Mongodb Atlas时,multer具有MemoryStorage的存储选项,并且尝试使用MemoryStorage将图像上传到Atlas。但是我面临的问题是我没有将数据发送到Nodejs的格式。我使用FormData()将图像详细信息发送到Nodejs。选择格式或包或在任何地方都可能是错误的。如果在任何地方都发现错误,请更正。下面是所有代码。

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;

头像路线

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

反应本机代码


//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!');
       });
  };

我可以通过其他任何方式上传图片吗?任何帮助将不胜感激。

0 个答案:

没有答案