Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read file with content-URI in React Native on Android?

I'm using React Native (0.48.3) for Android development. It seems, I'm stuck with a really trivial task: select a file and read it's content as a string. I have react-native-document-picker v2.0.0 for file selection, and it works fine: I can choose file and get it's URI. The problem is, I cannot make any package to read file with this link. I've already tried react-native-filesystem and react-native-fs, but it seems, they can work only with files in application directory. Anyway I get an error like this:

Error: File was not found: content://com.android.providers.downloads.documents/document/7

What package or function I need to use?

UPD: retrieving real, not content:// path, with react-native-get-real-path makes things work. But is this conversion really necessary, can one use content:// path for loading files?

like image 816
JustLogin Avatar asked Sep 18 '17 11:09

JustLogin


2 Answers

Say you are using react-native-fs, using copyFile can convert content uri to file uri.

if (url.startsWith('content://')) {
    const uriComponents = url.split('/')
    const fileNameAndExtension = urlComponents[uriComponents.length - 1]
    const destPath = `${RNFS.TemporaryDirectoryPath}/${fileNameAndExtension}`
    await RNFS.copyFile(uri, destPath)
}

Then you can use 'file://' + destPath as expected

like image 96
fujianjin6471 Avatar answered Nov 11 '22 10:11

fujianjin6471


There is already merged pull request #395 in react-native-fs which added a possibility to read from URI starting with content:// directly. I'm using Android URI in this code without any problem:

DocumentPicker.show({ filetype: ['*/*'] }, async (error, res) => {
  ...
  const exportedFileContent = await fs.readFile(res.uri, 'base64')
  ...
})
like image 32
jakubkoci Avatar answered Nov 11 '22 10:11

jakubkoci