Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-native How to open local file url using Linking?

I'm using the following code to download a file (can be a PDF or a DOC) and then opening it using Linking.

const { dirs } = RNFetchBlob.fs;
let config = {
    fileCache : true,
    appendExt : extension,
    addAndroidDownloads : {
        useDownloadManager : false,
        notification : false,
        title : 'File',
        description : 'A file.',
        path: `${dirs.DownloadDir}/file.${extension}`,
    },
};
RNFetchBlob.config(config)
    .fetch(
        method,
        remoteUrl,
        APIHelpers.getDefaultHeaders()
    )
    .then((res) => {
        let status = res.info().status;
        if (status == 200) {
            Linking.canOpenURL(res.path())
                .then((supported) => {
                    if (!supported) {
                        alert('Can\'t handle url: ' + res.path());
                    } else {
                        Linking.openURL(res.path())
                            .catch((err) => alert('An error occurred while opening the file. ' + err));
                    }
                })
                .catch((err) => alert('The file cannot be opened. ' + err));
        } else {
            alert('File was not found.')
        }
    })
    .catch((errorMessage, statusCode) => {
        alert('There was some error while downloading the file. ' + errorMessage);
    });

However, I'm getting the following error:

An error occurred while opening the file. Error: Unable to open URL: file:///Users/abhishekpokhriyal/Library/Developer/CoreSimulator/Devices/3E2A9C16-0222-40A6-8C1C-EC174B6EE9E8/data/Containers/Data/Application/A37B9D69-583D-4DC8-94B2-0F4AF8272310/Documents/RNFetchBlob_tmp/RNFetchBlobTmp_o259xexg7axbwq3fh6f4.pdf

I need to implement the solution for both iOS and Android.

like image 803
Abhishek Avatar asked Jan 23 '20 10:01

Abhishek


People also ask

How do I open an external URL in React Native?

Try this: import React, { useCallback } from "react"; import { Linking } from "react-native"; OpenWEB = () => { Linking. openURL(url); }; const App = () => { return <View onPress={() => OpenWeb}>OPEN YOUR WEB</View>; }; Hope this will solve your problem.


1 Answers

I think the easiest way to do so is by using react-native-file-viewer package.

It allows you to Prompt the user to choose an app to open the file with (if there are multiple installed apps that support the mimetype).

import FileViewer from 'react-native-file-viewer';

const path = // absolute-path-to-my-local-file.
FileViewer.open(path, { showOpenWithDialog: true })
.then(() => {
    // success
})
.catch(error => {
    // error
});
like image 73
sangaloma Avatar answered Sep 29 '22 12:09

sangaloma