Member-only story
How to Download Files in React Native
A concise and easy-to-follow guide on downloading files in React Native apps.
In a previous article, I showed you how to add the library to your project and how to use it for uploading files to a remote server. The steps for adding the library to your project can also be found there. (TLDR; yarn add rn-fetch-blob
).
Now, there’s some additional configuration that needs to be done in order to download files with RNFetchBlob.
Since we are going to use Android Download Manager, we have to add the following intent filter to AndroidManifest.xml
(app):
<intent-filter>
<action android:name="android.intent.action.DOWNLOAD_COMPLETE" /></intent-filter>
If you also plan on restricting the download to wifi, then you’ll also need the following permission in the manifest file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Let’s look at the code:
I’m going to break it down now.
Depending on the current platform, the file will be downloaded to DownloadDir
on Android, and to DocumentDir
on iOS. We’re using a selector to pick the correct one.
In the snippet, GenericFile is nothing but an interface that has some basic info about the file (name, extension, nothing much). You need to know the extension in order to correctly store the file on the device. Otherwise, you’ll run into a nightmare where the phone downloads .pdf and .png files which cannot be opened normally since they’re viewed as binary files.
Based on the extension, we select the correct mimeType. I had omitted the mime
field initially in the config. Oh man, how much useless debugging for such a little thing.
One small note on the manner in which the mimeType
has been determined in the snippet: it’s more of a proof of concept way. In a real-world app, you might want to refactor that. I’d…