react-native-fetch-blob

A module provides upload, download, and files access API. Supports file stream read/write for process large files.
Why do we need this
React Native does not support Blob
object at this moment, which means if you're going to send/receive binary data via fetch
API, that might not work as you expect. See facebook/react-native#854.
For some use cases, you might get into trouble. For example, displaying an image that requires a specific field in headers (ex. "Authorization : Bearer ...") or body, so you can't just pass the image uri to Image
component because that will probably returns a 401 response. Or you're going to upload binary data which generated from JS, the server will get an empry body due to this issue. With help of APIs provided by this module, you can send HTTP request with any headers, and decide how to handle the response/reqeust data without worry about if it is not supported by fetch
API. The response data can be just simply converted into BASE64 string, or stored to a file directly so that you can read it by using file access APIs such as readFile, readStream.
This module was designed to be a substitution of Blob
, there's a set of APIs including basic file system CRUD method, and file stream reader/writer. Also it has a special fetch
implementation that supports binary request/response body.
Backward Compatible
All updates are backward-compatible
generally you don't have to change existing code unless you're going to use new APIs. But we recommend pre 0.5.0
users consider upgrade the package to latest version, since we have introduced new APIs can either upload
or download
files simply using a file path. It's much more memory efficent in some use case. We've also introduced fs
APIs for access files, and file stream
API that helps you read/write files (especially for large ones), see Examples bellow. This module implements native methods, supports both Android (uses awesome native library AsyncHttpClient) and IOS.
TOC
Installation
Install package from npm
npm install --save react-native-fetch-blob
Link package using rnpm
rnpm link
Grant Permission to External storage for Android 5.0 or lower
Mechanism about granting Android permissions has slightly different since Android 6.0 released, please refer to Officail 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 AndroidManifetst.xml
.
<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" />
...
Also, if you're going to use Android Download Manager
you have to add this to AndroidManifetst.xml
<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 in Android 6.0 devices. To grant permissions in runtime, you might use modules like react-native-android-permissions.
Recipes
import RNFetchBlob from 'react-native-fetch-blob'
Download example : Fetch files that needs authorization token
RNFetchBlob.fetch('GET', 'http://www.example.com/images/img1.png', {
Authorization : 'Bearer access-token...',
})
.then((res) => {
let base64Str = res.base64()
let text = res.text()
let json = res.json()
})
.catch((errorMessage, statusCode) => {
})
Download to storage directly
The simplest way is give a fileCach
option to config, and set it to true
. This will let the incoming response data stored in a temporary path wihout any file extension.
These files won't be removed automatically, please refer to Cache File Management
RNFetchBlob
.config({
fileCache : true,
})
.fetch('GET', 'http://www.example.com/file/example.zip', {
some headers ..
})
.then((res) => {
console.log('The file saved to ', res.path())
})
Set Temp File Extension
Sometimes you might need a file extension for some reason. For instance, when using file path as source of Image
component, the path should end with something like .png or .jpg, you can do this by add appendExt
option to config
.
RNFetchBlob
.config({
fileCache : true,
appendExt : 'png'
})
.fetch('GET', 'http://www.example.com/file/example.zip', {
some headers ..
})
.then((res) => {
console.log('The file saved to ', res.path())
imageView = <Image source={{ uri : Platform.OS === 'android' ? 'file://' : '' + res.path() }}/>
})
Use Specific File Path
If you prefer a specific path rather than random generated one, you can use path
option. We've added a constant dirs in v0.5.0 that contains several common used directories.
let dirs = RNFetchBlob.fs.dirs
RNFetchBlob
.config({
path : dirs.DocumentDir + '/path-to-file.anything'
})
.fetch('GET', 'http://www.example.com/file/example.zip', {
})
.then((res) => {
console.log('The file saved to ', res.path())
})
These files won't be removed automatically, please refer to Cache File Management
Upload example : Dropbox files-upload API
react-native-fetch-blob
will convert the base64 string in body
to binary format using native API, this process will be done in a new thread, so it's async.
RNFetchBlob.fetch('POST', 'https://content.dropboxapi.com/2/files/upload', {
Authorization : "Bearer access-token...",
'Dropbox-API-Arg': JSON.stringify({
path : '/img-from-react-native.png',
mode : 'add',
autorename : true,
mute : false
}),
'Content-Type' : 'application/octet-stream',
}, base64ImageString)
.then((res) => {
console.log(res.text())
})
.catch((err) => {
})
Upload a file from storage
If you're going to use a file
request body, just wrap the path with wrap
API.
RNFetchBlob.fetch('POST', 'https://content.dropboxapi.com/2/files/upload', {
Authorization : "Bearer access-token...",
'Dropbox-API-Arg': JSON.stringify({
path : '/img-from-react-native.png',
mode : 'add',
autorename : true,
mute : false
}),
'Content-Type' : 'application/octet-stream',
}, RNFetchBlob.wrap(PATH_TO_THE_FILE))
.then((res) => {
console.log(res.text())
})
.catch((err) => {
})
Multipart/form-data example : Post form data with file and data
In version >= 0.3.0
you can also post files with form data, just put an array in body
, with elements have property name
, data
, and filename
(optional).
Elements have property filename
will be transformed into binary format, otherwise it turns into utf8 string.
RNFetchBlob.fetch('POST', 'http://www.example.com/upload-form', {
Authorization : "Bearer access-token",
otherHeader : "foo",
'Content-Type' : 'multipart/form-data',
}, [
{ name : 'avatar', filename : 'avatar.png', data: binaryDataInBase64},
{ name : 'name', data : 'user'},
{ name : 'info', data : JSON.stringify({
mail : 'example@example.com',
tel : '12345678'
})},
]).then((resp) => {
}).catch((err) => {
})
What if you want to upload a file in some field ? Just like upload a file from storage example, wrap data
by 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 file to form data.
RNFetchBlob.fetch('POST', 'http://www.example.com/upload-form', {
Authorization : "Bearer access-token",
otherHeader : "foo",
'Content-Type' : 'multipart/form-data',
}, [
{
name : 'avatar',
filename : 'avatar.png',
data: RNFetchBlob.wrap(PATH_TO_THE_FILE)
},
{
name : 'ringtone',
filename : 'ring.mp3',
type : 'application/mp3',
data : RNFetchBlob.wrap(RNFetchBlob.fs.asset('default-ringtone.mp3'))
}
{ name : 'name', data : 'user'},
{ name : 'info', data : JSON.stringify({
mail : 'example@example.com',
tel : '12345678'
})},
]).then((resp) => {
}).catch((err) => {
})
Upload/Download progress
In version >= 0.4.2
it is possible to know the upload/download progress. On Anroid, only download progress is supported. See wiki for more information.
RNFetchBlob.fetch('POST', 'http://www.example.com/upload', {
... some headers,
'Content-Type' : 'octet-stream'
}, base64DataString)
.progress((received, total) => {
console.log('progress', received / total)
})
.then((resp) => {
})
.catch((err) => {
})
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 Download Manager
.
Media Scanner
Media scanner scan the file and categorize by given MIME type, if MIME type not specified, it will try to resolve the file using its file extension.
RNFetchBlob
.config({
path : dirs.DCIMDir + '/music.mp3'
})
.fetch('GET', 'http://example.com/music.mp3')
.then((res) => RNFetchBlob.fs.scanFile([ { path : res.path(), mime : 'audio/mpeg' } ]))
.then(() => {
})
.catch((err) => {
})
Download Manager
When download large files on Android it is recommended to use Download Manager
, it supports lot of native features like progress bar, and notification, also the download task will be handled by OS, and more effective.
When using DownloadManager, fileCache
and path
properties in config
will not take effect, because Android DownloadManager can only store files to external storage. When download complete, DownloadManager will generate a file path so that you can deal with it.
RNFetchBlob
.config({
addAdnroidDownloads : {
useDownloadManager : true,
notification : false,
mime : 'text/plain',
description : 'File downloaded by download manager.'
}
})
.fetch('GET', 'http://example.com/file/somefile')
.then((resp) => {
resp.path()
})
Download Notification and Visibiliy in Download App (Android Only)
If you want to display a notification when file's completely download to storage (as the above), or make the downloaded file visible in "Downloads" app. You have to add some options to config
.
RNFetchBlob.config({
fileCache : true,
addAndroidDownloads : {
notification : true,
title : 'Great ! Download Success ! :O ',
description : 'An image file.',
mime : 'image/png',
meidaScannable : true,
}
})
.fetch('GET', 'http://example.com/image1.png')
.then(...)
File Access
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, every one who use this moudle may need these APIs for there cases.
Before get started using file APIs we recommend read Differences between File Source first.
File Access APIs
See File API for more information
File Stream
In v0.5.0
we've added writeStream
and readStream
, which allows your app read/write data from file path. This API creates a file stream, rather than convert whole data into BASE64 encoded string, it's handy when processing large files.
When calling readStream
method, you have to open
the stream, and start to read data.
let data = ''
RNFetchBlob.fs.readStream(
'base64',
PATH_TO_THE_FILE,
4095)
.then((ifstream) => {
ifstream.open()
ifstream.onData((chunk) => {
data += chunk
})
ifstream.onError((err) => {
console.log('oops', err)
})
ifstream.onEnd(() => {
<Image source={{ uri : 'data:image/png,base64' + data }}
})
})
When use writeStream
, the stream is also opened immediately, but you have to write
, and close
by yourself.
RNFetchBlob.fs.writeStream(
PATH_TO_FILE,
'utf8',
true)
.then((ofstream) => {
ofstream.write('foo')
ofstream.write('bar')
ofstream.close()
})
Cache File Management
When using fileCache
or path
options along with fetch
API, response data will automatically stored into file system. The files will NOT removed unless you unlink
it. There're several ways to remove the files
RNFetchblob.config({
fileCache : true
})
.fetch('GET', 'http://example.com/download/file')
.then((res) => {
res.flush()
})
RNFetchBlob.fs.unlink('some-file-path').then(() => {
})
You can also grouping requests by using session
API, and use dispose
to remove them all when needed.
RNFetchblob.config({
fileCache : true
})
.fetch('GET', 'http://example.com/download/file')
.then((res) => {
res.session('foo')
})
RNFetchblob.config({
session : 'foo'
fileCache : true
})
.fetch('GET', 'http://example.com/download/file')
.then((res) => {
})
RNFetchBlob.session('foo').add('some-file-path')
RNFetchBlob.session('foo').remove('some-file-path')
RNFetchBlob.session('foo').list()
RNFetchBlob.session('foo').dispose().then(() => { ... })
Self-Signed SSL Server
By default, react-native-fetch-blob does NOT allow connection to unknown certification provider since it's dangerous. If you're going to connect a server with self-signed certification, add trusty
to config
. This function is available for version >= 0.5.3
RNFetchBlob.config({
trusty : true
})
.then('GET', 'https://mysite.com')
.then((resp) => {
})
Changes
Version | |
---|
0.6.2 | Add support of asset file and camera roll files, Support custom MIME type when sending multipart request, thanks @smartt |
0.6.1 | Fix #37 progress report API issue on IOS |
0.6.0 | Add readFile and writeFile API for easier file access, also added Android download manager support. |
0.5.8 | Fix #33 PUT request will always be sent as POST on Android |
0.5.7 | Fix #31 #30 Xcode pre 7.3 build error |
0.5.6 | Add support for IOS network status indicator. Fix file stream ASCII reader bug. |
0.5.5 | Remove work in progress code added in 0.5.2 which may cause memory leaks. |
0.5.4 | Fix #30 #31 build build error, and improve memory efficiency. |
0.5.3 | Add API for access untrusted SSL server |
0.5.2 | Fix improper url params bug #26 and change IOS HTTP implementation from NSURLConnection to NSURLSession |
0.5.0 | Upload/download with direct access to file storage, and also added file access APIs |
0.4.2 | Supports upload/download progress |
0.4.1 | Fix upload form-data missing file extension problem on Android |
0.4.0 | Add base-64 encode/decode library and API |
~0.3.0 | Upload/Download octet-stream and form-data |
Development
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.