In order to publish new releases from this fork, we have renamed this project to
rn-fetch-blob and published to
Note: If upgrading from the original fork change all references in your project from
rn-fetch-blob. This includes
android/**/*.gradle depending on the platform used, failing to do so may cause build errors.
A project committed to making file access and data transfer easier and more efficient for React Native developers.
For Firebase Storage solution, please upgrade to the latest version for the best compatibility.
- Transfer data directly from/to storage without BASE64 bridging
- File API supports regular files, Asset files, and CameraRoll files
- Native-to-native file manipulation API, reduce JS bridging performance loss
- File stream support for dealing with large file
- Blob, File, XMLHttpRequest polyfills that make browser-based library available in RN (experimental)
- JSON stream supported base on Oboe.js @jimhigson
Wiki to get the complete documentation)TOC (visit
- HTTP Data Transfer
- Regular Request
- Download file
- Upload file
- Multipart/form upload
- Upload/Download progress
- Cancel HTTP request
- Android Media Scanner, and Download Manager Support
- Self-Signed SSL Server
- Transfer Encoding
- Drop-in Fetch Replacement
- File System
- File access
- File stream
- Manage cached files
- Web API Polyfills
- Performance Tips
- API References
This project was started in the cause of solving issue facebook/react-native#854, React Native's lacks of
Blob implementation which results into problems when transferring binary data.
It is committed to making file access and transfer easier and more efficient for React Native developers. We've implemented highly customizable filesystem and network module which plays well together. For example, developers can upload and download data directly from/to storage, which is more efficient, especially for large files. The file system supports file stream, so you don't have to worry about OOM problem when accessing large files.
0.8.0 we introduced experimental Web API polyfills that make it possible to use browser-based libraries in React Native, such as, FireBase JS SDK
Install package from npm
npm install --save rn-fetch-blob
Or if using CocoaPods, add the pod to your
pod 'rn-fetch-blob', :path => '../node_modules/rn-fetch-blob'
0.10.3 you can install this package directly from Github
# replace <branch_name> with any one of the branchesnpm install --save github:joltup/rn-fetch-blob#<branch_name>
Manually Link Native Modules
If automatically linking doesn't work for you, see instructions on manually linking.
Automatically Link Native Modules
For 0.29.2+ projects, simply link native packages via the following command (note: rnpm has been merged into react-native)
As for projects < 0.29 you need
rnpm to link native packages
Optionally, use the following command to add Android permissions to
RNFB_ANDROID_PERMISSIONS=true react-native link
pre 0.29 projects
RNFB_ANDROID_PERMISSIONS=true rnpm link
The link script might not take effect if you have non-default project structure, please visit the wiki to link the package manually.
Grant Permission to External storage for Android 5.0 or lower
The mechanism for granting Android permissions has slightly different since Android 6.0 released, please refer to Official Document.
If you're going to access external storage (say, SD card storage) for
Android 5.0 (or lower) devices, you might have to add the following line to
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.rnfetchblobtest"android:versionCode="1"android:versionName="1.0"><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>+ <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />+ <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />...
Also, if you're going to use
Android Download Manager you have to add this to
<intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" />+ <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/></intent-filter>
Grant Access Permission for Android 6.0
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. So adding permissions in
AndroidManifest.xml won't work for Android 6.0+ devices. To grant permissions in runtime, you might use PermissionAndroid API.
The module uses ES6 style export statement, simply use
import to load the module.
If you're using ES5 require statement to load the module, please add
default. See here for more detail.
var RNFetchBlob = require('rn-fetch-blob').default
HTTP Data Transfer
0.8.0 rn-fetch-blob automatically decides how to send the body by checking its type and
Content-Type in the header. The rule is described in the following diagram
To sum up:
- To send a form data, the
Content-Typeheader does not matter. When the body is an
Arraywe will set proper content type for you.
- To send binary data, you have two choices, use BASE64 encoded string or path points to a file contains the body.
- If the
application/octetthe given body will be considered as a BASE64 encoded data which will be decoded to binary data as the request body.
- Otherwise, if a string starts with
RNFetchBlob-file://(which can simply be done by
RNFetchBlob.wrap(PATH_TO_THE_FILE)), it will try to find the data from the URI string after
RNFetchBlob-file://and use it as the request body.
- To send the body as-is, simply use a
Content-Typeheader not containing
It is Worth to mentioning that the HTTP request uses cache by default, if you're going to disable it simply add a Cache-Control header
'Cache-Control' : 'no-store'
After 0.9.4, we disabled
Chunkedtransfer encoding by default, if you're going to use it, you should explicitly set header
Download example: Fetch files that need authorization token
Most simple way is download to memory and stored as BASE64 encoded string, this is handy when the response data is small. Note that when it comes to authorization, not only can you use an authorization token, but this package will automatically pass the cookies created by normal js requests such as axios and fetch. Therefore, if you are using traditional cookie-based ways to authorize your user, you don't need to do anything before this package works.
// send http request in a new thread (using native code)RNFetchBlob// Something went wrong:
Download to storage directly
If the response data is large, that would be a bad idea to convert it into BASE64 string. A better solution is streaming the response directly into a file, simply add a
fileCache option to config, and set it to
true. This will make incoming response data stored in a temporary path without any file extension.
These files won't be removed automatically, please refer to Cache File Management
Set Temp File Extension
Sometimes you might need a file extension for some reason. For example, when using file path as the source of
Image component, the path should end with something like .png or .jpg, you can do this by add
appendExt option to
Use Specific File Path
If you prefer a particular file path rather than randomly generated one, you can use
path option. We've added several constants in v0.5.0 which represents commonly used directories.
let dirs = RNFetchBlobfsdirsRNFetchBlob
These files won't be removed automatically, please refer to Cache File Management
files-upload APIUpload example : Dropbox
rn-fetch-blob will convert the base64 string in
body to binary format using native API, this process is done in a separated thread so that it won't block your GUI.
Upload a file from storage
If you're going to use a
file as request body, just wrap the path with
Multipart/form-data example: Post form data with file and data
version >= 0.3.0 you can also post files with form data, just put an array in
body, with elements have property
Elements have property
filename will be transformed into binary format, otherwise, it turns into utf8 string.
What if you want to append a file to form data? Just like upload a file from storage example, wrap
wrap API (this feature is only available for
version >= v0.5.0). On version >=
0.6.2, it is possible to set custom MIME type when appending a file to form data. But keep in mind when the file is large it's likely to crash your app. Please consider use other strategy (see #94).
version >= 0.4.2 it is possible to know the upload/download progress. After
0.7.0 IOS and Android upload progress are also supported.
RNFetchBlob// listen to upload progress event// listen to download progress event
0.9.6, you can specify an object as the first argument which contains
interval, to the frequency of progress event (this will be done in the native context a reduce RCT bridge overhead). Notice that
count argument will not work if the server does not provide response content length.
RNFetchBlob// listen to upload progress event, emit every 250ms// listen to download progress event, every 10%
0.7.0 it is possible to cancel an HTTP request. Upon cancellation, it throws a promise rejection, be sure to catch it.
let task = RNFetchBlobtask// handle request cancelled rejection// cancel the request, the callback function is optionaltask
Drop-in Fetch Replacement
If you have existing code that uses
whatwg-fetch(the official fetch), it's not necessary to replace them with
RNFetchblob.fetch, you can simply use our Fetch Replacement. The difference between Official them is official fetch uses whatwg-fetch which wraps XMLHttpRequest polyfill under the hood. It's a great library for web developers, but does not play very well with RN. Our implementation is simply a wrapper of our
fs APIs, so you can access all the features we provided.
Android Media Scanner, and Download Manager Support
If you want to make a file in
External Storage becomes visible in Picture, Downloads, or other built-in apps, you will have to use
Media Scanner or
Media scanner scans the file and categorizes by given MIME type, if MIME type not specified, it will try to resolve the file using its file extension.
When downloading large files on Android it is recommended to use
Download Manager, it supports a lot of native features like the progress bar, and notification, also the download task will be handled by OS, and more efficient.
When using DownloadManager,
path properties in
config will not take effect, because Android DownloadManager can only store files to external storage, also notice that Download Manager can only support
GET method, which means the request body will be ignored.
When download complete, DownloadManager will generate a file path so that you can deal with it.
Your app might not have right to remove/change the file created by Download Manager, therefore you might need to set custom location to the download task.
Download Notification and Visibility in Download App (Android Only)
If you need to display a notification upon the file is downloaded to storage (as the above) or make the downloaded file visible in "Downloads" app. You have to add some options to
Open Downloaded File with Intent
This is a new feature added in
0.9.0 if you're going to open a file path using official Linking API that might not work as expected, also, if you're going to install an APK in
Downloads app, that will not function too. As an alternative, you can try
actionViewIntent API, which will send an ACTION_VIEW intent for you which uses the given
Download and install an APK programmatically
const android = RNFetchBlobandroidRNFetchBlob
Or show an image in image viewer
File access APIs were made when developing
v0.5.0, which helping us write tests, and was not planned to be a part of this module. However, we realized that it's hard to find a great solution to manage cached files, everyone who uses this module may need these APIs for their cases.
Before start using file APIs, we recommend read Differences between File Source first.
File Access APIs
- asset (0.6.2)
- writeFile (0.6.0)
- appendFile (0.6.0)
- readFile (0.6.0)
- hash (0.10.9)
- scanFile (Android only)
See File API for more information
v0.5.0 we've added
readStream, which allows your app read/write data from the file path. This API creates a file stream, rather than convert entire data into BASE64 encoded string. It's handy when processing large files.
readStream method, you have to
open the stream, and start to read data. When the file is large, consider using an appropriate
interval to reduce the native event dispatching overhead (see Performance Tips)
The file stream event has a default throttle(10ms) and buffer size which preventing it cause too much overhead to main thread, yo can also tweak these values.
let data = ''RNFetchBlobfs
writeStream, the stream object becomes writable, and you can then perform operations like
Since version 0.10.9
write() resolves with the
RNFetchBlob instance so you can promise-chain write calls:
RNFetchBlobfs// Use array destructuring to get the stream object from the first item of the array we get from Promise.all()
You should NOT do something like this:
RNFetchBlobfs// Cannot catch any write() errors!
The problem with the above code is that the promises from the
ofstream.write() calls are detached and "Lost".
That means the entire promise chain A) resolves without waiting for the writes to finish and B) any errors caused by them are lost.
That code may seem to work if there are no errors, but those writes are of the type "fire and forget": You start them and then turn away and never know if they really succeeded.
Cache File Management
path options along with
fetch API, response data will automatically store into the file system. The files will NOT removed unless you
unlink it. There're several ways to remove the files
// remove file using RNFetchblobResponse.flush() object methodRNFetchblob// remove file by specifying a pathRNFetchBlobfs
You can also group requests by using
session API and use
dispose to remove them all when needed.
RNFetchblobRNFetchblob// or put an existing file path to the sessionRNFetchBlob// remove a file path from the sessionRNFetchBlob// list paths of a sessionRNFetchBlob// remove all files in a sessionRNFetchBlob
Chunked transfer encoding is disabled by default due to some service provider may not support chunked transfer. To enable it, set
Transfer-Encoding header to
Self-Signed SSL Server
By default, rn-fetch-blob does NOT allow connection to unknown certification provider since it's dangerous. To connect a server with self-signed certification, you need to add
config explicitly. This function is available for version >=
Web API Polyfills
0.8.0 we've made some Web API polyfills that makes some browser-based library available in RN.
- XMLHttpRequest (Use our implementation if you're going to use it with Blob)
Here's a sample app that uses polyfills to upload files to FireBase.
Read Stream and Progress Event Overhead
If the process seems to block JS thread when file is large when reading data via
fs.readStream. It might because the default buffer size is quite small (4kb) which result in a lot of events triggered from JS thread. Try to increase the buffer size (for example 100kb = 102400) and set a larger interval (available for 0.9.4+, the default value is 10ms) to limit the frequency.
Reduce RCT Bridge and BASE64 Overhead
React Native connects JS and Native context by passing JSON around React Native bridge, and there will be an overhead to convert data before they sent to each side. When data is large, this will be quite a performance impact to your app. It's recommended to use file storage instead of BASE64 if possible.The following chart shows how much faster when loading data from storage than BASE64 encoded string on iPhone 6.
ASCII Encoding has /terrible Performance
Concat and Replacing Files
If you're going to concatenate files, you don't have to read the data to JS context anymore! In
0.8.0 we introduced new encoding
uri for writeFile and appendFile API, which make it possible to handle the whole process in native.
- This library does not urlencode unicode characters in URL automatically, see #146.
- When you create a
Blob, from an existing file, the file WILL BE REMOVED if you
- If you replaced
window.XMLHttpRequestfor some reason (e.g. make Firebase SDK work), it will also affect how official
fetchworks (basically it should work just fine).
- When file stream and upload/download progress event slow down your app, consider an upgrade to
0.9.6+, use additional arguments to limit its frequency.
- When passing a file path to the library, remove
See release notes
If you're interested in hacking this module, check our development guide, there might be some helpful information. Please feel free to make a PR or file an issue.