简体   繁体   中英

Open .pdf, .docx, .xlsx, etc with default device application in React Native

I am trying to open .pdf, .docx, .xlsx and other similar files using React Native.

I am currently downloading the files from an amazon s3 bucket to the device, then attempting to open them on the device using react-native-fetch-blob android.actionViewIntent(res.path(), mimeType) .

This works fine with images, but with anything else I'm getting the following error:

Error: No Activity found to handle Intent { act=android.intent.action.VIEW dat=file:///storage/emulated/0/Android/data/myappname/files/1475.pdf typ=application/pdf flg=0x10000000 }

EDIT: For anyone here who would like to see the implementation that ended up working (using react-native-file-system and react-native-fetch-blob):

const fileType = fileDownloadPath.split('.').pop();
const SavePath = Platform.OS === 'ios' ? RNFS.DocumentDirectoryPath : RNFS.ExternalDirectoryPath;
const mimeType = getMimeType(fileType); // getMimeType is a method (switch statement) that returns the correct mimetype
const path = `${SavePath}/${filename}.${fileType}`;
const android = RNFetchBlob.android;

RNFS.downloadFile({
  fromUrl: url,
  toFile: path,
}).promise.then(() => {
  android.actionViewIntent(path, mimeType)
    .then((success) => {
      console.log('success: ', success)
    })
    .catch((err) => {
      console.log('err:', err)
    })
});

Apparently your device doesn't have other file viewer applications installed such as Polaris office or Office suite or any other of those kind file viewers.

Typically this is the exception you get for this kind of issues. You can either show a warning/toast or show some links to download these apps from play store.

I had this and it's a way to solve it.

  try{
    startActivity(intent);
  } catch (ActivityNotFoundException e){
    Toast.makeText(MainActivity.this,
            "Error showing pdf", Toast.LENGTH_LONG).show();
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM