NIKHIL MISHRA
NIKHIL MISHRA

Reputation: 1

How to open a selected file in react native

My problem is in opening file using react-native-file-viewer after selecting file from react-native-document-picker and saving it to a react state. I am trying pdf file for simplicity. This is not working in android 13 but working in android 10.

In my react native app I am using react-native-document-picker to select a file, I am storing this file to a react state and passing to to axios service in form data, and it is saving successfully.

import DocumentPicker from 'react-native-document-picker'; const [selectedFile, setSelectedFile] = useState(null);

try {
            const res = await DocumentPicker.pick({
                type: [
                    DocumentPicker.types.pdf,  // For PDFs
                    DocumentPicker.types.images,  // For images (.jpg, .png)
                    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',  // For XLSX files
                    'application/vnd.openxmlformats-officedocument.presentationml.presentation',  // For PPT files
                    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',  // For DOCX files
                ],
            });
            setSelectedFile(res[0]); // Store the selected fil
        } catch (err) {
            if (DocumentPicker.isCancel(err)) {
                console.log("file upload canceled");
            } else {
                throw err;
            }
        }

Now I am trying to open this file (saved in state) using its default viewer app, before saving it to axios, after selecting the file from device, I am able to show selected file name.

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

    if (selectedFile) {
      try {
        // Use the file's URI to open it
        await FileViewer.open(selectedFile.uri);
        console.log('File opened successfully');
      } catch (err) {
        console.error('Error opening file:', err);
        Alert.alert('Error', 'Unable to open the file.', err);
      }
    } else {
      Alert.alert('No file selected', 'Please select a file first.');
    }

It is giving error [Error: No app associated with this mime type]

I have tried asking for READ_EXTERNAL_STORAGE permission

try {
            const granted = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE);
            if (granted) {
                console.log("Storage permission is already granted");
                return; // Permission is already granted, no need to request
            }

            // Request storage permission if not already granted
            const result = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE);

            if (result === PermissionsAndroid.RESULTS.GRANTED) {
                console.log("Storage permission granted");
            } else {
                console.log("Storage permission denied");
                Alert.alert(
                    "Storage Permission Required",
                    "Please enable storage permissions in the app settings.",
                    [{ text: "OK" }]
                );
            }
        } catch (err) {
            console.error('Error requesting storage permission:', err);
        }

but it is showing Storage Permission Required without asking for permission. This is not working in android 13 but working in android 10.

I have also tried to convert file uri to format /data/user/0/com.appName/cache/document%3A1000032725 to 'content://com.android.providers.media.documents/document/document%3A1000032725 using react-native-fs

import RNFS from 'react-native-fs';
 const getActualPathFromContentUri = async (contentUri) => {
        const path = RNFS.TemporaryDirectoryPath + '/' + contentUri.split('/').pop();
        try {
            await RNFS.copyFile(contentUri, path);
            return path;
        } catch (err) {
            console.error('Error copying file to temporary directory:', err);
            throw err;
        }
    };
    const getFilePathFromUri = async (uri) => {
        if (Platform.OS === 'android' && uri.startsWith('content://')) {
            try {
                const filePath = await getActualPathFromContentUri(uri);
                console.log('File path from URI:', filePath);
                return filePath;
            } catch (err) {
                console.error('Error getting file path:', err);
            }
        }
        return uri; // If not Android or no content URI, return the original URI
    };
   

    // Usage Example
    const openFile = async () => {
        if (selectedFile) {
            const fileName = selectedFile.name;
            const extension = fileName.split('.').pop();
            const filePath = await getFilePathFromUri(selectedFile.uri);
            try {
                await FileViewer.open(filePath);
                console.log('File opened successfully');
            } catch (err) {
                console.error('Error opening file:', err);
            }
        } else {
            console.log('No file selected');
        }
    };

It is showing message in console File opened successfully but unable to open file.

Upvotes: 0

Views: 85

Answers (0)

Related Questions