0

Is it possible to upload file (images) to server with react-native using FormData? Tried to use it like this:

var data = new FormData();
  data.append('file', file);
  console.log(JSON.stringify(data));
  var id = 5;
  fetch('http://192.168.1.104:3000/app/complaint/uploadFile?id='+id,{
    method:'POST',
    body: data,
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'multipart/form-data;',
    },
  });

For React, FormData works as expected but for React-Native not working.

I have also tried (used in react - working)

const data = fetch('http://192.168.1.104:3000/app/complaint/uploadFile?id='+id, {
        credentials: "same-origin",
        method:'POST',
        body: dataval,
        timeout: 1000000000,
      });  

But nothing works,

In the back-end server, I am upload using

var d = require('domain').create()    
d.run(function safelyUpload () {
        var file=req.file('file').upload({dirname: path.resolve(sails.config.appPath, folder),
        }, function whenDone(err, uploadedFiles) {
          if (err) return res.serverError(err);
          else{
            sails.log.debug('Complaint File data : ' +util.inspect(uploadedFiles, {showHidden: true,depth: null}));
          }
        });
});

Is there any other ways

Amr Labib
  • 3,995
  • 3
  • 19
  • 31
San Daniel
  • 165
  • 1
  • 3
  • 15

1 Answers1

1

Here is example to upload image using Fetch API

const photo = {
  uri: user.profilePicture,
  type: 'image/jpeg',
  name: 'photo.jpg',
};

const form = new FormData();
form.append("ProfilePicture", photo);

fetch(
  URL,
  {
    body: form,
    method: "PUT",
    headers: {
      'Content-Type': 'multipart/form-data',
      'Authorization': 'Bearer ' + user.token
    }
  }
).then((response) => response.json())
.catch((error) => {
  alert("ERROR " + error)
})
.then((responseData) => {
  alert("Succes "+ responseData)
}).done();

Credits https://stackoverflow.com/a/36649457/5315786

Pir Shukarullah Shah
  • 4,124
  • 2
  • 22
  • 42
  • thanks @Pir Shukarullah Shah It just worked by replace data.append('file',file); ===> data.append('file', { uri: file.uri, type: 'image/jpeg', name: 'testPhotoName' }); It worked , I don't know how, the file object also contains uri, type. However the problem is solved – San Daniel Dec 28 '17 at 07:38