|
| 1 | +# react-native-fetch-blob [](https://badge.fury.io/js/react-native-fetch-blob) |
| 2 | + |
| 3 | +A react-native module for fetch file/image with custom headers, supports blob response data. |
| 4 | + |
| 5 | +If you're dealing with image or file server that requires an `Authorization` token in the header, or you're having problem with `fetch` API when receiving blob data, you might try this module (this is also the reason why I made this). |
| 6 | + |
| 7 | +See [[fetch] Does fetch with blob() marshal data across the bridge?](https://github.com/facebook/react-native/issues/854). |
| 8 | + |
| 9 | +This module enables you upload/download binary data in js, see [Examples](#user-content-usage) bellow. |
| 10 | + |
| 11 | +The source code is very simple, just an implementation of native HTTP request, supports both Android (uses awesome native library [AsyncHttpClient](https://github.com/AsyncHttpClient/async-http-client])) and IOS. |
| 12 | + |
| 13 | +## Usage |
| 14 | + |
| 15 | +* [Installation](#user-content-installation) |
| 16 | +* [Examples](#user-content-usage) |
| 17 | + * [Download file](#user-content-download-example--fetch-files-that-needs-authorization-token) |
| 18 | + * [Upload file](#user-content-upload-example--dropbox-files-upload-api) |
| 19 | + * [Multipart/form upload](#user-content-multipartform-data-example--post-form-data-with-file-and-data) |
| 20 | +* [API](#user-content-api) |
| 21 | + |
| 22 | +## Installation |
| 23 | + |
| 24 | +Install package from npm |
| 25 | + |
| 26 | +```sh |
| 27 | +npm install --save react-native-fetch-blob |
| 28 | +``` |
| 29 | + |
| 30 | +Link package using [rnpm](https://github.com/rnpm/rnpm) |
| 31 | + |
| 32 | +```sh |
| 33 | +rnpm link |
| 34 | +``` |
| 35 | + |
| 36 | +## Usage |
| 37 | + |
| 38 | +```js |
| 39 | +import RNFetchBlob from 'react-native-fetch-blob' |
| 40 | +``` |
| 41 | +#### Download example : Fetch files that needs authorization token |
| 42 | + |
| 43 | +```js |
| 44 | + |
| 45 | +// send http request in a new thread (using native code) |
| 46 | +RNFetchBlob.fetch('GET', 'http://www.example.com/images/img1.png', { |
| 47 | + Authorization : 'Bearer access-token...', |
| 48 | + // more headers .. |
| 49 | + }) |
| 50 | + // when response status code is 200 |
| 51 | + .then((res) => { |
| 52 | + // the conversion is done in native code |
| 53 | + let base64Str = res.base64() |
| 54 | + // the following conversions are done in js, it's SYNC |
| 55 | + let text = res.text() |
| 56 | + let json = res.json() |
| 57 | + |
| 58 | + }) |
| 59 | + // Status code is not 200 |
| 60 | + .catch((errorMessage, statusCode) => { |
| 61 | + // error handling |
| 62 | + }) |
| 63 | +``` |
| 64 | + |
| 65 | +#### Upload example : Dropbox [files-upload](https://www.dropbox.com/developers/documentation/http/documentation#files-upload) API |
| 66 | + |
| 67 | +`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. |
| 68 | + |
| 69 | +```js |
| 70 | + |
| 71 | +RNFetchBlob.fetch('POST', 'https://content.dropboxapi.com/2/files/upload', { |
| 72 | + Authorization : "Bearer access-token...", |
| 73 | + 'Dropbox-API-Arg': JSON.stringify({ |
| 74 | + path : '/img-from-react-native.png', |
| 75 | + mode : 'add', |
| 76 | + autorename : true, |
| 77 | + mute : false |
| 78 | + }), |
| 79 | + 'Content-Type' : 'application/octet-stream', |
| 80 | + }, base64ImageString) |
| 81 | + .then((res) => { |
| 82 | + console.log(res.text()) |
| 83 | + }) |
| 84 | + .catch((err) => { |
| 85 | + // error handling .. |
| 86 | + }) |
| 87 | +``` |
| 88 | + |
| 89 | +#### Multipart/form-data example : Post form data with file and data |
| 90 | + |
| 91 | +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). |
| 92 | + |
| 93 | +Elements have property `filename` will be transformed into binary format, otherwise it turns into utf8 string. |
| 94 | + |
| 95 | +```js |
| 96 | + |
| 97 | + RNFetchBlob.fetch('POST', 'http://www.example.com/upload-form', { |
| 98 | + Authorization : "Bearer access-token", |
| 99 | + otherHeader : "foo", |
| 100 | + 'Content-Type' : 'multipart/form-data', |
| 101 | + }, [ |
| 102 | + // element with property `filename` will be transformed into `file` in form data |
| 103 | + { name : 'avatar', filename : 'avatar.png', data: binaryDataInBase64}, |
| 104 | + // elements without property `filename` will be sent as plain text |
| 105 | + { name : 'name', data : 'user'}, |
| 106 | + { name : 'info', data : JSON.stringify({ |
| 107 | + mail : 'example@example.com', |
| 108 | + tel : '12345678' |
| 109 | + })}, |
| 110 | + ]).then((resp) => { |
| 111 | + // ... |
| 112 | + }).catch((err) => { |
| 113 | + // ... |
| 114 | + }) |
| 115 | +``` |
| 116 | + |
| 117 | +## API |
| 118 | + |
| 119 | +#### `fetch(method, url, headers, body):Promise<FetchBlobResponse> ` |
| 120 | + |
| 121 | +Send a HTTP request uses given headers and body, and return a Promise. |
| 122 | + |
| 123 | +#### method:`string` Required |
| 124 | +HTTP request method, can be one of `get`, `post`, `delete`, and `put`, case-insensitive. |
| 125 | +#### url:`string` Required |
| 126 | +HTTP request destination url. |
| 127 | +#### headers:`object` (Optional) |
| 128 | +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). |
| 129 | +#### body:`string | Array<Object>` (Optional) |
| 130 | +Body of the HTTP request, body can either be a BASE64 string, or an array contains object elements, each element have 2 required property `name`, and `data`, and 1 optional property `filename`, once `filename` is set, content in `data` property will be consider as BASE64 string that will be converted into byte array later. |
| 131 | + |
| 132 | +When body is a base64 string , this string will be converted into byte array in native code, and the request body will be sent as `application/octet-stream`. |
| 133 | + |
| 134 | +#### `base64` |
| 135 | + |
| 136 | +A helper object simply uses [base-64](https://github.com/mathiasbynens/base64) for decode and encode BASE64 data. |
| 137 | + |
| 138 | +```js |
| 139 | +RNFetchBlob.base64.encode(data) |
| 140 | +RNFetchBlob.base64.decode(data) |
| 141 | +``` |
| 142 | + |
| 143 | +### FetchBlobResponse |
| 144 | + |
| 145 | +When `fetch` success, it resolve a `FetchBlobResponse` object as first argument. `FetchBlobResponse` object has the following methods (these method are synchronous, so you might take quite a performance impact if the file is big) |
| 146 | + |
| 147 | +#### base64():string |
| 148 | + returns base64 string of response data (done in native context) |
| 149 | +#### json():object |
| 150 | + returns json parsed object (done in js context) |
| 151 | +#### text():string |
| 152 | + returns decoded base64 string (done in js context) |
| 153 | + |
| 154 | + |
| 155 | +### TODO |
| 156 | + |
| 157 | +* Save file to storage |
| 158 | +* Custom MIME type in form data |
0 commit comments