是否可以从React-Native中的图像获取二进制数据? [英] Is it possible to get the binary data from an image in React-Native?

查看:1057
本文介绍了是否可以从React-Native中的图像获取二进制数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用react-native-camera,但在获取图像作为react-native中的二进制数据时遇到了麻烦.我需要此功能才能将图像上传到我们的后端.我唯一要获取的是对图像的uri,然后可能将其作为FormData发送到服务器,但是不建议这样做,因为这需要对我们的后端进行一些基础结构更改.

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.

推荐答案

如果要从 react-native-camera 获取图像作为二进制数据.我建议使用 react-native-fs 来阅读uri

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

示例

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

如果要通过FormData上传图像,我建议 rn-fetch-blob

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

示例

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

这篇关于是否可以从React-Native中的图像获取二进制数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆