【问题标题】:React Native download and open file - file is blank on AndroidReact Native 下载和打开文件 - Android 上的文件是空白的
【发布时间】:2021-07-22 16:28:13
【问题描述】:

所以,我使用 react-native-fs 从 URL 下载文件,然后使用 react-native-file-viewer 打开以查看/共享/打印它们。这适用于 iOS,但在 Android 上存在问题。我假设文件正在正确下载,因为当传递FileViewer 文件的路径时,它会“打开”文件。虽然,显示的只是一个空白屏幕。

这是我的实现:

  const fileName = 'AnImageFile.png';
  const dir = RNFS.DocumentDirectoryPath;
  const filePath = dir + '/' + fileName;

  const options = {
    fromUrl: url,
    toFile: filePath,
  };

  RNFS.downloadFile(options)
  .promise.then(() => FileViewer.open(filePath, {showOpenWithDialog: true, showAppsSuggestions: true}))
  .then(() => {
    console.log('File should have opened');
    // Hits here, opens blank on Android
  })
  .catch((error) => {
    console.log('There was an error opening the file');
    console.log(error);
  });

Screenshot of image being opened

我也尝试使用rn-fetch-blob 而不是react-native-fs 来下载文件。但是,当从该路径传递FileViewer 时,它无法找到该文件。我认为我更接近使用react-native-fs 的上述解决方案,因为文件下载并且可以定位,但我对此可能完全错误。任何意见或建议将不胜感激。

【问题讨论】:

    标签: android react-native react-native-fs rn-fetch-blob


    【解决方案1】:

    想通了,发布以防万一这对其他人有用...如果您在android上尝试下载然后打开一个文件并且它打开为空白,您很可能没有权限。这与您使用哪种文件查看和下载工具无关。 https://github.com/joltup/rn-fetch-blob/issues/483#issuecomment-761763626

    我使用的解决方案:

    RNFS.downloadFile(options)
      .promise.then(()=> PermissionsAndroid.requestMultiple([
        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
      ]))
      .then((result) => {
        const isGranted = result[PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE] === 'granted' 
        && result[PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE] === 'granted';
    
        isGranted ? FileViewer.open(filePath, {showOpenWithDialog: true, showAppsSuggestions: true}) : console.log('Declined')})
      .then(() => {
        console.log('File should have opened');
      })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-28
      • 1970-01-01
      • 1970-01-01
      • 2016-12-05
      相关资源
      最近更新 更多