【问题标题】:Open .pdf, .docx, .xlsx, etc with default device application in React Native在 React Native 中使用默认设备应用程序打开 .pdf、.docx、.xlsx 等
【发布时间】:2017-02-26 04:23:46
【问题描述】:

我正在尝试使用 React Native 打开 .pdf、.docx、.xlsx 和其他类似文件。

我目前正在将文件从 amazon s3 存储桶下载到设备,然后尝试使用 react-native-fetch-blob android.actionViewIntent(res.path(), mimeType) 在设备上打开它们。

这适用于图像,但其他任何我得到以下错误:

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 }

编辑:对于希望看到最终工作的实现的任何人(使用 react-native-file-system 和 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)
    })
});

【问题讨论】:

  • 您确定android.actionViewIntent(res.path(), mimeType) 可以处理图像文件吗?我尝试使用 source uri = res.path() 显示 png ,它可以工作。但是使用android.actionViewIntent(res.path(), 'image/png'),它会在图库应用中显示“无法生成缩略图”。

标签: android react-native


【解决方案1】:

显然您的设备没有安装其他文件查看器应用程序,例如 Polaris office 或 Office 套件或任何其他此类文件查看器。

通常这是您遇到此类问题的例外情况。您可以显示警告/toast 或显示一些链接以从 Play 商店下载这些应用程序。

【讨论】:

  • 效果很好,非常感谢!我选择了 OfficeSuite。当抛出错误时,我可能最终会显示警报,让他们知道他们需要下载适当的查看器。感谢您的帮助!
  • @albeee @Nader 从 url 获取图像后,我需要将其存储到外部存储中吗?因为我看到纳德的代码在 Android 上使用了RNFS.ExternalDirectoryPath
  • 最终通过将路径设置为 Android 的 RNFS.ExternalDirectoryPath 和 iOS 的 RNFS.DocumentDirectoryPath 来传递它。默认情况下保留它会导致浏览器应用程序中出现“没有这样的文件”消息。
  • 什么是 RNFS for android 编程方法?
【解决方案2】:

我有这个,这是解决它的一种方法。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 2019-05-07
    • 1970-01-01
    相关资源
    最近更新 更多