Monday, 8 May 2017

Send a file from react-native to Node js server

I'm doing an application with react-native. Now I'm trying to send an image from the mobile to the server (Node Js). For this I'm using react-native-image-picker. And the problem is that when I send the image it save a file but it's empty not contain the photo. I think that the problem probably is that the server can't access to the path of the image because is in a different device. But I don't know how I can do it.

React-Native:

openImagePicker(){
      const options = {
        title: 'Select Avatar',
         storageOptions: {
          skipBackup: true,
          path: 'images'
      }
      }

      ImagePicker.showImagePicker(options, (imagen) =>{
          if (imagen.didCancel) {
        console.log('User cancelled image picker');
      }
      else if (imagen.error) {
        console.log('ImagePicker Error: ', imagen.error);
      }
      else if (imagen.customButton) {
        console.log('User tapped custom button: ', imagen.customButton);
      }
      else {
    let formdata = new FormData();
    formdata.append("file[name]", imagen.fileName);
    formdata.append("file[path]", imagen.path);
    formdata.append("file[type]", imagen.type);
            fetch('http://X/user/photo/58e137dd5d45090d0b000006', {
      method: 'PUT',
      headers: {
         'Content-Type': 'multipart/form-data'
      },
      body: formdata
    })
        .then(response => {
          console.log("ok");       
      })
       .catch(function(err) {
          console.log(err);
      })  
    }})}

Node Js:

    addPhotoUser = function (req, res) {
User.findById(req.params.id, function(err, user) {
fs.readFile(req.body.file.path, function (err, data) {      
  var pwd = 'home/ubuntu/.../';
  var newPath = pwd + req.body.file.name;
  fs.writeFile(newPath, data, function (err) {
    imageUrl: URL + req.body.file.name;
        user.save(function(err) {
            if(!err) {
                console.log('Updated');
            } else {
                console.log('ERROR: ' + err);
            }
            res.send(user);
        });

  });
});
});
};



via david raja

No comments:

Post a Comment