React Native下载并打开文件-文件在Android上为空

xdnvmnnf  于 2023-01-11  发布在  Android
关注(0)|答案(2)|浏览(183)

所以,我使用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的解决方案,因为文件可以下载并找到,但是我可能完全错了。任何输入或建议都将不胜感激。

ar5n3qh5

ar5n3qh51#

我想出来了,如果你在android上尝试下载,然后打开一个文件,它打开时是空白的,那么你很可能没有权限。这与你使用的文件查看和下载工具无关。https://github.com/joltup/rn-fetch-blob/issues/483#issuecomment-761763626
溶液I:

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');
  })
nnt7mjpx

nnt7mjpx2#

export const downloadFile = async (path, url) => {
 const filePath = RNFS.DocumentDirectoryPath + '/' + path + '/' + 
  'video.mp4';

 RNFS.downloadFile({
      fromUrl: url,
      toFile: filePath,
      background: false,
      cacheable: false,
      connectionTimeout: 60 * 1000,
      readTimeout: 120 * 1000,
 }).promise.then((r) => {
 console.log('promise result: ', r);

    FileViewer.open(filePath, {showOpenWithDialog: true, 
      showAppsSuggestions: true}) : console.log('Declined')});
   });
 };

相关问题