如何使用 React Native 下载文件? [英] How to download a file with React Native?

查看:36
本文介绍了如何使用 React Native 下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am building an app with React Native, for Android and iOS. I am trying to let the user download a PDF file when clicking on a button.

  • react-native-file-download 不支持 Android
  • react-native-fs 在我触发 downloadFile 时什么也不做(没有显示在通知栏),之后我找不到该文件.我将 android.permission.WRITE_EXTERNAL_STORAGE 添加到 Android 清单文件中.我仔细检查了我尝试下载的文件是否存在(如果不存在,库会抛出错误)
  • react-native-file-download does not support Android
  • react-native-fs does nothing when I trigger downloadFile (nothing shows up on the notification bar), and I am not able to find the file after that. I added android.permission.WRITE_EXTERNAL_STORAGE to the Android Manifest file. I double-checked that the file I am trying to download exists (when it does not, the library throws an error)

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

I do not find other solutions for this problem. I have found libraries for viewing a PDF, but I would like to let the user download the PDF.

推荐答案

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

Just implemented the download feature an hour ago :p

请按照以下步骤操作:

a) npm install rn-fetch-blob

a) npm install rn-fetch-blob

b) 按照安装说明进行操作.

b) follow the installation instructions.

b2) 如果你想在不使用 rnpm 的情况下手动安装包,去他们的 维基.

b2) if you want to manually install the package without using rnpm, go to their wiki.

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

c) Finally, that's how I made it possible to download files within my app:

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

这篇关于如何使用 React Native 下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆