React Native File constructor

I have redux actions that are being used in web. We are using these actions in react native project, so that we can share logic between web and native and only change the components.

One of these actions (image upload) takes File as parameter. We managed how to get an image info in react native - we are using 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. I cannot use some alternatives to File, because redux action that is shared between web and native expects File.

How can I create File in react-native?

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:

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

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

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue