简体   繁体   English

反应本机文件构造函数

[英]React Native File constructor

I have redux actions that are being used in web.我有在 web 中使用的 redux 操作。 We are using these actions in react native project, so that we can share logic between web and native and only change the components.我们在 react native 项目中使用了这些操作,这样我们就可以在 web 和 native 之间共享逻辑,并且只更改组件。

One of these actions (image upload) takes File as parameter.这些操作之一(图像上传)将File作为参数。 We managed how to get an image info in react native - we are using react-native-image-picker .我们设法在 react native 中获取图像信息 - 我们正在使用react-native-image-picker When user picks an image, it returns response with all the data.当用户选择一张图片时,它会返回包含所有数据的响应。

let file = new File([atob(response.data)],
      response.fileName,
      {type: response.type})

However, this doesn't work in react native, there is no File constructor as is on web.但是,这在本机反应中不起作用,没有像 Web 上那样的File构造函数。 I cannot use some alternatives to File , because redux action that is shared between web and native expects File .我不能使用File一些替代方法,因为在 web 和 native 之间共享的 redux action 需要File

How can I create File in react-native?如何在 react-native 中创建File

AFAIK you cannot create a file even on web, even more, if you try to get the keys of a File object with Object.keys() you'll not get anything, i dont know if is because it means to be a representation of a file on the browser, but what you can actually use is Blob , that is Binary Large Object File, basically a file in memory, if you're getting the data from an endpoint, use: AFAIK 你甚至不能在网络上创建一个文件,甚至更多,如果你尝试使用Object.keys()获取 File 对象的键,你将不会得到任何东西,我不知道是否是因为它意味着是浏览器上的一个文件,但您实际上可以使用的是Blob ,即二进制大对象文件,基本上是内存中的文件,如果您从端点获取数据,请使用:

fetch('/endpoint')
.then(res) {
  res.blob()
}
.then(blob) {
 // Do whatever you want with your blob
}

if not, you can do new Blob([response.data], {type: response.type}) Note that the blobs doesnt have names, you'll handle that with a library later如果没有,您可以执行new Blob([response.data], {type: response.type})请注意,blob 没有名称,稍后您将使用库处理它

This Library https://github.com/wkh237/react-native-fetch-blob and documentation https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API could be useful这个库https://github.com/wkh237/react-native-fetch-blob和文档https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API可能是有用的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM