faizalk faizalk - 7 months ago 89
Android Question

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)

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"


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