React-Native send image file from XHR to Api

We are creating a photo upload function in our application, which is built using the native reaction.

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

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

I can also get base64 encoded base64 encoded, but I do not want to deal with base64, as it slows down the application, and the result is about 1/3 of the larger request.

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

I wanted to try:

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 that the content is sent, not the URI string itself. Any help please?

+4
source share
1 answer

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

// File api.js

'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
source

Source: https://habr.com/ru/post/1626367/


All Articles