React Native:将本地图像读取为 Base64 字符串以在 JSON 中发送

React Native: Read local image as Base64 string to send it in JSON

在 React Native 中,我试图加载存储在 相对路径中的图像作为 base64 字符串,但是 require returns 3 作为响应而不是图像源。

我确信路径是正确的,并且我的 require 命令在我的 Reacy Native JSX 代码的其他地方工作,从相同的相对路径 (<Image source={require('../resources/examplecar.jpg')}>) 加载图像没有任何问题。

如何从文件系统获取本地图像源作为 base64 字符串以在 JSON 中发送?

var body = {
    path: '../resources/examplecar.jpg',
    data: {
        image: require('../resources/examplecar.jpg'),
    }
}

require 中不能有变量。它不适用于 rn 中的图像源。 做

  image: require('../resources/examplecar.jpg')

使用 RNFS 插件可以访问 React Native 资产并将数据转换为多种格式,包括 Base64。

imageData = await RNFS.readFile(RNFS.MainBundlePath+"/assets/resources/examplecar.jpg", 'base64').then();