react-native-fs: for existed file 'content://' exists returns false

I have image file (obtained by using device camera) with following uri content://media/external/images/media/331 using RNFS.exists.then returns false while file is exists. how to fix this?

About this issue

  • Original URL
  • State: open
  • Created 6 years ago
  • Reactions: 6
  • Comments: 20 (3 by maintainers)

Most upvoted comments

Here’s a workaround until we get native support:

await Promise.all(arrayOfFilesWithContentUris.map(async (file) => {
  const file = await RNFS.stat(file.uri);
  console.log(file.originalFilepath);
  // will now output a regular file url, compatible with other functions, e.g.:
  // RNFS.unlink(file.originalFilepath);
}));

I ran into this issue recently when trying to upload a file that was shared to my app (via the react-native-share-menu module). The file that it was trying to upload started with content:// and so while RNFS.stat as well as RNFS.uploadFiles threw an exception when trying to handle that file, RNFS.copyFile could work with it just fine. So here’s my workaround:

let fileName = sharedItem.data.split('\\').pop().split('/').pop()
let filePath = sharedItem.data
        
if (Platform.OS === 'android') {
  try {
    let ext = null

    switch(sharedItem.mimeType) {
      case 'image/jpeg':
        ext = 'jpg'
        break
      case 'image/png':
        ext = 'png'
        break
      default:
        Alert.alert('Unsupported file type.')
        this.setState({ loading: false })
        return
    }

    fileName = fileName + '.' + ext
    filePath = RNFS.DocumentDirectoryPath + '/' + fileName

    await RNFS.copyFile(sharedItem.data, filePath)
  } catch (err) {
    log('File Read Error:', err)
    Alert.alert('An unknown error occured while reading your file.')
    this.setState({ loading: false })
    return
  }
}

const files = [
  {
    name: 'image',
    filename: fileName,
    filepath: filePath,
    filetype: sharedItem.mimeType
  }
]

// and then RNFS.uploadFiles as usual

Basically, I’m just copying the file over to my app’s own directory for handling. But with the web server I was uploading the images to, the file extension is required and in this case the file extension wasn’t in the file path, luckily the share module gives me the MIME type and my application only supports a limited number of types so I was able to make do.

@llaine Use RNFS.stat should do the trick.