'How to effectively open downloaded file in external application using expo linking

I'm downloading a file from an URI, and trying to open it in another application. This file is a simple .xlsx spreadsheet. I'm using an Android device to test. In the code below is a reproduceble example:

import React, { useCallback } from 'react'
import { Button, View } from 'react-native'
import * as Linking from 'expo-linking'
import * as FileSystem from 'expo-file-system'

const App = () => {
  const download = useCallback(async () => {
    const downloadUri = 'http://url.to/my/spreadsheet.xlsx')
    const localPath = `${FileSystem.cacheDirectory}spreadsheet.xlsx`
    try {
      await FileSystem.downladAsync(downloadUri, localPath)
        .then(async ({ uri }) => {
          const contentURL = await FileSystem.getContentUriAsync(uri)
          await Linking.openURL(contentURL)
        })
        .catch((err) => console.log(err))
    } catch (err) {
      console.log(err)
    }
  }, [])

  return (
    <View>
      <Button onPress={download}>
        Pree Me!
      </Button>
    </View>
  )
}

No error is displayed in the console log, however when the Linking is attempting to open the file gives the error "Google Sheets was unable to open your Spreadsheet". The same thing happens when I'm trying to open other filetypes as:

  • .docx with Google Docs
  • .pptx with Google Slides
  • .pdf with Drive
  • ... and so on

Any idea what could be causing this?

NOTE

I verified if the file returned by the URL is not corrupted using:

curl -X GET http://url.to/my/spreadsheet.xlsx -o spreadsheet.xlsx (from within the device) and it could be opened normally with Google Sheets.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source