# react-native-fetch-blob [](https://badge.fury.io/js/react-native-fetch-blob) 
## v0.5.0 Work In Progress README.md
A react-native module for upload, and download file with custom headers. Supports blob response data, upload/download progress, and file reader API that enables you process file content in js context (such as display image data, string or image process).
If you're dealing with image or file server that requires special field in the header, or you're having problem with `fetch` API when receiving blob data, you might try this module.
See [[fetch] Does fetch with blob() marshal data across the bridge?](https://github.com/facebook/react-native/issues/854) for the reason why we made this module.
In latest version (v0.5.0), you can upload/download files directly with file path. We've also introduced `file stream` API for reading **large files** from storage, see [Examples](#user-content-usage) bellow.
This module implements native HTTP request, supports both Android (uses awesome native library [AsyncHttpClient](https://github.com/AsyncHttpClient/async-http-client])) and IOS.
## Usage
* [Installation](#user-content-installation)
* [Examples](#user-content-usage)
* [Download file](#user-content-download-example--fetch-files-that-needs-authorization-token)
* [Upload file](#user-content-upload-example--dropbox-files-upload-api)
* [Multipart/form upload](#user-content-multipartform-data-example--post-form-data-with-file-and-data)
* [Upload/Download progress](#user-content-uploaaddownload-progress)
* [Deal with files in storage](#user-content-deal-with-files-in-storage)
* [Release cache files](#user-content-release-cache-files)
* [API](#user-content-api)
## Installation
Install package from npm
```sh
npm install --save react-native-fetch-blob
```
Link package using [rnpm](https://github.com/rnpm/rnpm)
```sh
rnpm link
```
## Usage
```js
import RNFetchBlob from 'react-native-fetch-blob'
```
#### Download example : Fetch files that needs authorization token
```js
// send http request in a new thread (using native code)
RNFetchBlob.fetch('GET', 'http://www.example.com/images/img1.png', {
Authorization : 'Bearer access-token...',
// more headers ..
})
// when response status code is 200
.then((res) => {
// the conversion is done in native code
let base64Str = res.base64()
// the following conversions are done in js, it's SYNC
let text = res.text()
let json = res.json()
})
// Status code is not 200
.catch((errorMessage, statusCode) => {
// error handling
})
```
#### Download to storage directly
If you want to save the response data directly into file storage rather than convert response data into base64 for some reason.
Put a `config` before calling `fetch`. There're three options which are `path`, `fileCache`, and `appendExt` that let you decide how and where to save the file.
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.
```js
RNFetchBlob
.config({
fileCache : true,
})
.fetch('GET', 'http://www.example.com/file/example.zip', {
some headers ..
})
.then((res) => {
// the temp file path
console.log('The file saved to ', res.path())
})
```
But in some cases, you might need a file extension even the file is temporary cached. For instance, when use the file path as source of `Image` element the path should end with something like .png or .jpg, you can do this by put one more option in to `config`.
```js
RNFetchBlob
.config({
fileCache : true,
appendExt : 'png'
})
.fetch('GET', 'http://www.example.com/file/example.zip', {
some headers ..
})
.then((res) => {
// the temp file path with file extension `png`
console.log('The file saved to ', res.path())
// Beware that when using a file path as Image source on Android,
// you must prepend "file://"" before the file path
imageView =
})
```
What's more, if you prefer a specific path, rather a random generated path, you can use `path` option. We've added a [getSystemDirs](#user-content-getsysdirs) API in v0.5.0 that lists several common used directories.
```js
RNFetchBlob.getSystemDirs().then((dirs) => {
RNFetchBlob
.config({
path : dirs.DocumentDir + 'path-to-file.anything'
})
.fetch('GET', 'http://www.example.com/file/example.zip', {
some headers ..
})
.then((res) => {
// the path should be dirs.DocumentDir + 'path-to-file.anything'
console.log('The file saved to ', res.path())
})
})
```
#### Upload example : Dropbox [files-upload](https://www.dropbox.com/developers/documentation/http/documentation#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.
```js
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) => {
// error handling ..
})
```
#### Upload a file from storage
If you're going to use a `file` in file system as request body, just push the path with prefix `RNFetchBlob-file://`.
```js
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-file://' + PATH_TO_THE_FILE)
.then((res) => {
console.log(res.text())
})
.catch((err) => {
// error handling ..
})
```
#### 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 object elements with property `name`, `data`, and `filename`(optional).
Elements have property `filename` will be transformed into binary format, otherwise it turns into utf8 string.
```js
RNFetchBlob.fetch('POST', 'http://www.example.com/upload-form', {
Authorization : "Bearer access-token",
otherHeader : "foo",
'Content-Type' : 'multipart/form-data',
}, [
// element with property `filename` will be transformed into `file` in form data
{ name : 'avatar', filename : 'avatar.png', data: binaryDataInBase64},
// elements without property `filename` will be sent as plain text
{ name : 'name', data : 'user'},
{ name : 'info', data : JSON.stringify({
mail : 'example@example.com',
tel : '12345678'
})},
]).then((resp) => {
// ...
}).catch((err) => {
// ...
})
```
What if some fields contains a file in file storage ? Just like [upload a file from storage](#user-content-upload-a-file-from-storage) example, change the `data` to path of the file with a prefix `RNFetchBlob-file://`
```js
RNFetchBlob.fetch('POST', 'http://www.example.com/upload-form', {
Authorization : "Bearer access-token",
otherHeader : "foo",
'Content-Type' : 'multipart/form-data',
}, [
// append field data from file path
{ name : 'avatar', filename : 'avatar.png', data: 'RNFetchBlob-file://' + PATH_TO_THE_FILE},
// elements without property `filename` will be sent as plain text
{ 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.
```js
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) => {
// ...
})
```
## API
#### `fetch(method, url, headers, body):Promise`
Send a HTTP request uses given headers and body, and return a Promise.
#### method:`string` Required
HTTP request method, can be one of `get`, `post`, `delete`, and `put`, case-insensitive.
#### url:`string` Required
HTTP request destination url.
#### headers:`object` (Optional)
Headers of HTTP request, value of headers should be `stringified`, if you're uploading binary files, content-type should be `application/octet-stream` or `multipart/form-data`(see examples above).
#### body:`string | Array