如何使用 React Native 下载文件?

新手上路,请多包涵

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

  • react-native-file-download 不支持安卓
  • 当我触发 downloadFile 时 react-native-fs 什么都不做(通知栏上没有显示任何内容),之后我无法找到该文件。我在 Android 清单文件中添加了 android.permission.WRITE_EXTERNAL_STORAGE 。我仔细检查了我要下载的文件是否存在(如果不存在,库会抛出错误)

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

原文由 Arnaud 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
1 个回答

一个小时前刚刚实现了下载功能:p

按着这些次序:

a) npm install rn-fetch-blob

b) 遵循安装说明。

b2) 如果您想在不使用 rnpm 的情况下手动安装软件包,请访问他们的 wiki

c)最后,这就是我在我的应用程序中下载文件的方式:

 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
})

原文由 Ray 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题