How to download a file with React Native?

只谈情不闲聊 提交于 2019-11-28 19:25:41
Ray

Just implemented the download feature an hour ago :p

Follow these steps:

a) npm install rn-fetch-blob

b) follow the installation instructions.

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

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

If you're using Expo, react-native-fetch-blob won't work. Use FileSystem.

Here's a working example:

const { uri: localUri } = await FileSystem.downloadAsync(remoteUri, FileSystem.documentDirectory + 'name.ext');

Now you have localUri with the path to the downloaded file. Feel free to set your own filename instead of name.ext.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!