faizalk
faizalk

Reputation: 3

Uploading an Image from React Native to Loopback API with Fetch

Hello This is my first time trying to build an API. What I am trying to do is send an image saved on my phone through react-native to a loopback container that would save the image on my computer. I'm having trouble formatting the form data correctly so the image will be accepted by loopback. I've been trying:

let photo = {names: 'file', uri:'file:///storage/emulated/0/Pictures/IMG_20161028_094032.jpg'}
let formdata = new FormData();
formdata.append(photo.names, photo.uri)

fetch('http://192.168.0.15:3000/api/containers/container2/upload',{
method: 'POST',
body: formdata
}).then(response => {
}).catch(err => {
})

The response I get back is:

_bodyText: '{"result":{"files":{},"fields":{"file":["file:///storage/emulated/0/Pictures/IMG_20161028_094032.jpg"]}}}' }

Which is incorrect because the file should be in "files" and not "fields"

Upvotes: 0

Views: 605

Answers (1)

BradByte
BradByte

Reputation: 11093

Try using xhr instead of fetch. This is the example provided by Facebook for this scenario...

// Polyfill for XMLHttpRequest2 FormData API, allowing multipart POST requests with 
// mixed data (string, native files) to be submitted via XMLHttpRequest.

var photo = {
  uri: uriFromCameraRoll,
  type: 'image/jpeg',
  name: 'photo.jpg',
};

var body = new FormData();
body.append('authToken', 'secret');
body.append('photo', photo);
body.append('title', 'A beautiful photo!');

xhr.open('POST', serverURL);
xhr.send(body);

Upvotes: 1

Related Questions