Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 416
nullforlife Avatar asked Feb 12 '18 13:02

nullforlife


People also ask

How do I fetch an image in react native?

Displaying Network Images To display images via Network requests, we have to use source property instead of require tag. The same way you can add the custom CSS properties to style the Image Component in React Native. You can place this code in any of your React Native template to show the image.

How do you call an image source react native?

Adding Image Let us create a new folder img inside the src folder. We will add our image (myImage. png) inside this folder. We will show images on the home screen.

Is image a react native component?

The React Native Image component provides some properties you can use to configure the component and display the images according to your team's business or technical needs.


1 Answers

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
);
like image 165
hawkup Avatar answered Sep 28 '22 00:09

hawkup