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

落爺英雄遲暮 提交于 2019-12-06 02:57:33

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/48747278/is-it-possible-to-get-the-binary-data-from-an-image-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!