4
votes

We are building a photo upload feature in our application, which is built using react native.

I am using this: https://github.com/marcshilling/react-native-image-picker

Upon selecting the image, I get the URI of the image, something like this: file:///storage/151A-3C1B/Pictures/image-c47d8624-8530-43df-873e-e31c2d27d0e9.jpg

I can also get the base64 encoded string of the image, but I do not want to deal with base64, since it slows down the app and the result is about 1/3 bigger request.

So my question is, I have the URI like above, how can I send the contents of the file to my API backend? It expects multipart/form-data, the name "photo".

I wanted to try with this:

var formData = new FormData();
formData.append('photo', CONTENTS);

But I do not know how to get the contents of the file, or how to pass the file URI to the formData object, so the contents would be sent, not the URI string itself. Any help please?

2
seems like need a native module - aboutqx
I agree that if I wanted to access filesystem, a native module would be required. I just read somewhere about only passing the URI of the file to the XHR and it would access the contents on its own, but that doesn't sound right. I might solve this using the base64 in the end, or using a native module. - tomazahlin

2 Answers

0
votes

You can try something like this. It worked for me :

// api.js file

'use strict';

import request from 'superagent';
import {NativeModules} from 'react-native';

var api = (method, URL) => {
  var r = request(method, apiURL);
  return r;
}

api.uploadPhoto = (fileName, fileUri, uri, callback) => {
  var upload = {
    uri: fileUri, // either an 'assets-library' url (for files from photo library) or an image dataURL
    uploadUrl: // your backend url here,
    fileName: fileName,
    mimeType: 'image/jpeg',
    headers: {},
    data: {}
  };

  NativeModules.FileTransfer.upload(upload, (err, res) => {
    console.log(err, res);
    if (err || res.status !== 200) {
      return callback(err || res.data || 'UNKNOWN NETWORK ERROR');
    }

    callback();
  });
};

export default api;

// you can then call your action this way

'use strict';

import request from './api';

request.uploadPhoto('picture', uri, apiURL, (err) => {
  if (err) {
    console.log(err);
    return;
  }
});
0
votes

This is an old post, but if it helps others this will do the trick:

var formData = new FormData();
formData.append("photo", {
    uri: imageUri,
    type: "image/jpg"
});
axios.post(serviceUrl, formData);