我正试图写一些代码来将照片数据保存到文件中.

我读入照片数据,它是react native(Expo)的base64字符串,然后我对其进行解码.我立即将解码后的字符串写入文件.

当我读到应该包含所有照片数据的文件时,我得到的只是4个字符,而我期望有很多兆字节的字符.

有人知道如何使用Expo将解码后的base64字符串写入文件吗?下面是我的代码...

  const fileUri = `${directoryPath}/${today.getTime()}/${fileName}`;

  // this reads us the base64 encoded image data
  const imageString = await FileSystem.readAsStringAsync(
    image.uri,
    { encoding: FileSystem.EncodingType.Base64 }
  );

  const fooString = Base64.decode(imageString);

  // write the decoded photo data to a file
  await FileSystem.writeAsStringAsync(fileUri, fooString);

  // read back the file so we can make sure all the data was written
  const blah = await FileSystem.readAsStringAsync(fileUri);

  const photoInfo = await FileSystem.getInfoAsync(fileUri);

  console.log({
    fileUri,
    fooStringLength: fooString.length,
    blahLength: blah.length,
    equals: blah === fooString,
    photoInfo
  });

你可以看到这很简单,所以我一定错过了什么?下面是这console.log个...

Object {
  "blahLength": 4,
  "equals": false,
  "fileUri": "file:///var/mobile/Containers/Data/Application/33EB7A6F-AA1A-42BF-B252-9A5088A906C6/Documents/ExponentExperienceData/%2540anonymous%252FWIB-mobile-12902e68-9c57-4230-a3df-aaa355c3edf1/20220328184945/1648511392902/Right.jpg.enc",
  "fooStringLength": 2953317,
  "photoInfo": Object {
    "exists": true,
    "isDirectory": false,
    "modificationTime": 1648511394.334474,
    "size": 4415423,
    "uri": "file:///var/mobile/Containers/Data/Application/33EB7A6F-AA1A-42BF-B252-9A5088A906C6/Documents/ExponentExperienceData/%2540anonymous%252FWIB-mobile-12902e68-9c57-4230-a3df-aaa355c3edf1/20220328184945/1648511392902/Right.jpg.enc",
  },
}

你可以看到长度不匹配.此外,如果我同时打印出fooStringblah,这是用于比较的前后字符串,fooString在我看来是正确的,我希望它看起来是正确的,但blah只相当于4个字符的数据.下面是blah字符串和文件的错误内容...

enter image description here

我修改了现有的零食以显示我的情况.该小吃提供了拍照或 Select 现有照片的选项.我将代码放入"从照片库处理程序中 Select 现有照片"中.这个小吃显示,当我将数据写入文件,然后将其读回时,数据不匹配.知道为什么吗?

https://snack.expo.dev/@rcoleils/camera

推荐答案

实际保存的是原始文件中的原始二进制数据,然后再读取回来.问题是,Expo with writeAsStringAsyncreadAsStringAsync并不支持它,因为它实际上不是一个字符串,而是任意的二进制数据.

这里有一个错误报告:https://github.com/expo/expo/issues/2453.到目前为止,它被忽略了,唯一的解决办法是保存原始的base64表示.虽然这可能会起作用,但它会使该文件对任何其他程序都没有用处,使其存储需求增加33%,并且在使用前需要进行特殊解码.

React-native相关问答推荐

Appcenter构建失败错误号::EEXIST -文件存在于syserr_fail2_in

使用react-native-reanimatedreact 导航崩溃

TextInput 中的大写文本 - react native

React-native 重置数据库

如何获取 iOS 版本?

react-native: 'adb' 不是内部或外部命令、可运行程序或批处理文件

React Native - 初始属性 Android

使用 .env 变量在 react-native 应用程序上设置 appcenter

如何在 React Native 中删除警告

React native + redux-persist:如何忽略键(黑名单)?

如何使用 Stripe (stripe.js) 和 react-native

axios 的网络错误和react-native

为什么,确切地说,我们需要 React.forwardRef?

使用带有样式组件的动画

无法识别的 WebSocket 连接选项 `agent`、`perMessageDeflate`、`pfx`、`key`、`passphrase`... 你的意思是把这些放在 `headers` 下吗?

更改按钮 colored颜色 onPress(切换功能)

如何隐藏 React Native NavigationBar

React-native iOS 不显示图像(pod 问题)

React Native:如何动态更改

安卓启动问题:Unsupported class file major version 57