如何使用 React Native 下载文件?

2024-05-07

我正在使用 React Native 为 Android 和 iOS 构建一个应用程序。我试图让用户在单击按钮时下载 PDF 文件。

  • 反应本机文件下载 https://www.npmjs.com/package/react-native-file-download不支持安卓
  • 反应本机FS https://github.com/itinance/react-native-fs当我触发 downloadFile 时什么也不做(通知栏上没有显示任何内容),之后我无法找到该文件。我添加了android.permission.WRITE_EXTERNAL_STORAGE到 Android 清单文件。我仔细检查了我尝试下载的文件是否存在(如果不存在,则库会抛出错误)

我没有找到这个问题的其他解决方案。我找到了用于查看 PDF 的库,但我想让用户下载 PDF。


按着这些次序:

  1. Run npm install rn-fetch-blob.

  2. 按照安装说明进行操作。如果您想在不使用 rnpm 的情况下手动安装软件包,请转到他们的wiki https://github.com/joltup/rn-fetch-blob/wiki/Manually-Link-Package#index.

  3. 最后,这就是我如何在我的应用程序中下载文件:

    const { config, fs } = RNFetchBlob
    let PictureDir = fs.dirs.PictureDir // this is the pictures directory. You can check the available directories in the wiki.
    let options = {
      fileCache: true,
      addAndroidDownloads : {
        useDownloadManager : true, // setting it to true will use the device's native download manager and will be shown in the notification bar.
        notification : false,
        path:  PictureDir + "/me_"+Math.floor(date.getTime() + date.getSeconds() / 2), // this is the path where your downloaded file will live in
        description : 'Downloading image.'
      }
    }
    config(options).fetch('GET', "http://www.example.com/example.pdf").then((res) => {
      // do some magic here
    })
    
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 React Native 下载文件? 的相关文章

随机推荐