React Native 文件构造函数

5 javascript android reactjs react-native

我有在网络中使用的 redux 操作。我们在 React Native 项目中使用这些操作,以便我们可以在 Web 和 Native 之间共享逻辑,并且只更改组件。

这些操作之一(图像上传)作为File参数。我们设法如何在本机反应中获取图像信息 - 我们正在使用react-native-image-picker. 当用户选择图像时,它会返回包含所有数据的响应。

let file = new File([atob(response.data)],
      response.fileName,
      {type: response.type})
Run Code Online (Sandbox Code Playgroud)

然而,这在 React Native 中不起作用,没有File像 Web 上那样的构造函数。我无法使用某些替代方案File,因为需要在 Web 和本机之间共享 redux 操作File

我如何File在react-native中创建?

Nah*_*ron 1

AFAIK 即使在网络上也无法创建文件,更重要的是,如果您尝试获取 File 对象的键,Object.keys()您将不会得到任何东西,我不知道是否是因为它意味着成为浏览器上文件的表示,但您实际可以使用的是Blob,即二进制大对象文件,基本上是内存中的文件,如果您从端点获取数据,请使用:

fetch('/endpoint')
.then(res) {
  res.blob()
}
.then(blob) {
 // Do whatever you want with your blob
}
Run Code Online (Sandbox Code Playgroud)

如果没有,你可以这样做new Blob([response.data], {type: response.type}) 注意,blob 没有名称,稍后你将使用库来处理它

该库https://github.com/wkh237/react-native-fetch-blob和文档https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API可以是有用