Is it possible to get the binary data from an image in React-Native?

nullforlife picture nullforlife · Feb 12, 2018 · Viewed 9.2k times · Source

I'm using react-native-camera and I'm having trouble getting the image as binary data in react-native. I need this to be able to upload images to our backend. The only thing I manage to get is uri's to the image and then maybe sending that as FormData to the server but that is not recommended as that would require some infrastructure change to our backend.

Is there anyone that know a solution or some tips regarding this issue?

Any thoughts or help is very much appreciated.

Answer

hawkup picture hawkup · Feb 12, 2018

If you want to get image as binary data from react-native-camera. I recommend to use react-native-fs to read uri

Example

const RNFS = require("react-native-fs");
// response.uri from react-native-camera
RNFS.readFile(response.uri, "base64").then(data => {
  // binary data
  console.log(data);
});

If you want to upload image via FormData I recommend rn-fetch-blob

Example

import RNFetchBlob from 'rn-fetch-blob'
// response.uri from react-native-camera
const path = response.uri.replace("file://", "");
const formData = [];
formData.push({
  name: "photo",
  filename: `photo.jpg`,
  data: RNFetchBlob.wrap(path)
});

let response = await RNFetchBlob.fetch(
  "POST",
  "https://localhost/upload",
  {
    Accept: "application/json",
    "Content-Type": "multipart/form-data"
  },
  formData
);