|
@@ -1,764 +0,0 @@
|
1
|
|
-# react-native-fetch-blob
|
2
|
|
-[![release](https://img.shields.io/github/release/wkh237/react-native-fetch-blob.svg?style=flat-square)](https://github.com/wkh237/react-native-fetch-blob/releases) [![npm](https://img.shields.io/npm/v/react-native-fetch-blob.svg?style=flat-square)](https://www.npmjs.com/package/react-native-fetch-blob) ![](https://img.shields.io/badge/PR-Welcome-brightgreen.svg?style=flat-square) [![](https://img.shields.io/badge/Wiki-Public-brightgreen.svg?style=flat-square)](https://github.com/wkh237/react-native-fetch-blob/wiki) [![npm](https://img.shields.io/npm/l/react-native-fetch-blob.svg?maxAge=2592000&style=flat-square)]()
|
3
|
|
-
|
4
|
|
-A project committed to make file acess and data transfer easier, efficient for React Native developers.
|
5
|
|
-
|
6
|
|
-## Features
|
7
|
|
-- Transfer data directly from/to storage without BASE64 bridging
|
8
|
|
-- File API supports normal files, Asset files, and CameraRoll files
|
9
|
|
-- Native-to-native file manipulation API, reduce JS bridging performance loss
|
10
|
|
-- File stream support for dealing with large file
|
11
|
|
-- Blob, File, XMLHttpRequest polyfills that make browser-based library available in RN (experimental)
|
12
|
|
-
|
13
|
|
-## TOC
|
14
|
|
-* [About](#user-content-about)
|
15
|
|
-* [Installation](#user-content-installation)
|
16
|
|
-* [HTTP Data Transfer](#user-content-http-data-transfer)
|
17
|
|
- * [Regular Request](#user-content-regular-request)
|
18
|
|
- * [Download file](#user-content-download-example--fetch-files-that-needs-authorization-token)
|
19
|
|
- * [Upload file](#user-content-upload-example--dropbox-files-upload-api)
|
20
|
|
- * [Multipart/form upload](#user-content-multipartform-data-example--post-form-data-with-file-and-data)
|
21
|
|
- * [Upload/Download progress](#user-content-uploaddownload-progress)
|
22
|
|
- * [Cancel HTTP request](#user-content-cancel-request)
|
23
|
|
- * [Android Media Scanner, and Download Manager Support](#user-content-android-media-scanner-and-download-manager-support)
|
24
|
|
- * [Self-Signed SSL Server](#user-content-self-signed-ssl-server)
|
25
|
|
- * [Transfer Encoding](#user-content-transfer-encoding)
|
26
|
|
- * [RNFetchBlob as Fetch](#user-content-rnfetchblob-as-fetch)
|
27
|
|
-* [File System](#user-content-file-system)
|
28
|
|
- * [File access](#user-content-file-access)
|
29
|
|
- * [File stream](#user-content-file-stream)
|
30
|
|
- * [Manage cached files](#user-content-cache-file-management)
|
31
|
|
-* [Web API Polyfills](#user-content-web-api-polyfills)
|
32
|
|
-* [Performance Tips](#user-content-performance-tips)
|
33
|
|
-* [API References](https://github.com/wkh237/react-native-fetch-blob/wiki/Fetch-API)
|
34
|
|
-* [Trouble Shooting](https://github.com/wkh237/react-native-fetch-blob/wiki/Trouble-Shooting)
|
35
|
|
-* [Development](#user-content-development)
|
36
|
|
-
|
37
|
|
-## About
|
38
|
|
-
|
39
|
|
-This project was initially for solving the issue [facebook/react-native#854](https://github.com/facebook/react-native/issues/854), because React Native lack of `Blob` implementation and it will cause some problem when transferring binary data. Now, this project is committed to make file access and transfer more easier, efficient for React Native developers. We've implemented highly customizable filesystem and network module which plays well together. For example, upload and download data directly from/to storage which is much more efficient in some cases(especially for large ones). The file system supports file stream, so you don't have to worry about OOM problem when accessing large files.
|
40
|
|
-
|
41
|
|
-In `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](https://github.com/wkh237/rn-firebase-storage-upload-sample)
|
42
|
|
-
|
43
|
|
-
|
44
|
|
-## Installation
|
45
|
|
-
|
46
|
|
-Install package from npm
|
47
|
|
-
|
48
|
|
-```sh
|
49
|
|
-npm install --save react-native-fetch-blob
|
50
|
|
-```
|
51
|
|
-
|
52
|
|
-Or if using CocoaPods, add the pod to your `Podfile`, for example:
|
53
|
|
-
|
54
|
|
-```
|
55
|
|
-pod 'react-native-fetch-blob,
|
56
|
|
- :path => '../node_modules/react-native-fetch-blob
|
57
|
|
-```
|
58
|
|
-
|
59
|
|
-**Automatically Link Native Modules**
|
60
|
|
-
|
61
|
|
-For 0.29.2+ projects, simply link native packages via following command because rnpm has been merged into react-native, you no longer need it.
|
62
|
|
-
|
63
|
|
-```
|
64
|
|
-react-native link
|
65
|
|
-```
|
66
|
|
-
|
67
|
|
-As for projects < 0.29 you need `rnpm` to link native packages
|
68
|
|
-
|
69
|
|
-```sh
|
70
|
|
-rnpm link
|
71
|
|
-```
|
72
|
|
-
|
73
|
|
-Optionally, use the following command to add Android permissions to `AndroidManifest.xml` automatically
|
74
|
|
-
|
75
|
|
-```sh
|
76
|
|
-RNFB_ANDROID_PERMISSIONS=true react-native link
|
77
|
|
-```
|
78
|
|
-
|
79
|
|
-pre 0.29 projects
|
80
|
|
-
|
81
|
|
-```sh
|
82
|
|
-RNFB_ANDROID_PERMISSIONS=true rnpm link
|
83
|
|
-```
|
84
|
|
-
|
85
|
|
-The link script might not take effect if you have non-default project structure, please visit [the wiki](https://github.com/wkh237/react-native-fetch-blob/wiki/Manually-Link-Package) to manually link the pacakge.
|
86
|
|
-
|
87
|
|
-**Grant Permission to External storage for Android 5.0 or lower**
|
88
|
|
-
|
89
|
|
-Mechanism about granting Android permissions has slightly different since Android 6.0 released, please refer to [Official Document](https://developer.android.com/training/permissions/requesting.html).
|
90
|
|
-
|
91
|
|
-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 `AndroidManifest.xml`.
|
92
|
|
-
|
93
|
|
-```diff
|
94
|
|
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
95
|
|
- package="com.rnfetchblobtest"
|
96
|
|
- android:versionCode="1"
|
97
|
|
- android:versionName="1.0">
|
98
|
|
-
|
99
|
|
- <uses-permission android:name="android.permission.INTERNET" />
|
100
|
|
- <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
|
101
|
|
-+ <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
102
|
|
-+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
103
|
|
-
|
104
|
|
- ...
|
105
|
|
-
|
106
|
|
-```
|
107
|
|
-
|
108
|
|
-Also, if you're going to use `Android Download Manager` you have to add this to `AndroidManifetst.xml`
|
109
|
|
-
|
110
|
|
-```diff
|
111
|
|
- <intent-filter>
|
112
|
|
- <action android:name="android.intent.action.MAIN" />
|
113
|
|
- <category android:name="android.intent.category.LAUNCHER" />
|
114
|
|
-+ <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
|
115
|
|
- </intent-filter>
|
116
|
|
-```
|
117
|
|
-
|
118
|
|
-**Grant Access Permission for Android 6.0**
|
119
|
|
-
|
120
|
|
-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](https://github.com/lucasferreira/react-native-android-permissions).
|
121
|
|
-
|
122
|
|
-## Usage
|
123
|
|
-
|
124
|
|
-ES6
|
125
|
|
-
|
126
|
|
-The module uses ES6 style export statement, simply use `import` to load the module.
|
127
|
|
-
|
128
|
|
-```js
|
129
|
|
-import RNFetchBlob from 'react-native-fetch-blob'
|
130
|
|
-```
|
131
|
|
-
|
132
|
|
-ES5
|
133
|
|
-
|
134
|
|
-If you're using ES5 require statement to load the module, please add `default`. See [here](https://github.com/wkh237/react-native-fetch-blob/wiki/Trouble-Shooting#rnfetchblobfetch-is-not-a-function) for more detail.
|
135
|
|
-
|
136
|
|
-```
|
137
|
|
-var RNFetchBlob = require('react-native-fetch-blob').default
|
138
|
|
-```
|
139
|
|
-
|
140
|
|
-## HTTP Data Transfer
|
141
|
|
-
|
142
|
|
-
|
143
|
|
-### Regular Request
|
144
|
|
-
|
145
|
|
-After `0.8.0` react-native-fetch-blob automatically decide how to send the body by checking its type and `Content-Type` in header. The rule is described in the following diagram
|
146
|
|
-
|
147
|
|
-<img src="img/RNFB-flow (1).png" style="width : 90%" />
|
148
|
|
-
|
149
|
|
-To sum up :
|
150
|
|
-
|
151
|
|
-- To send a form data, the `Content-Type` header does not matters. When the body is an `Array` we will set proper content type for you.
|
152
|
|
-- To send binary data, you have two choices, use BASE64 encoded string or path points to a file contains the body.
|
153
|
|
- - If the `Content-Type` containing substring`;BASE64` or `application/octet` the given body will be considered as a BASE64 encoded data which will be decoded to binary data as the request body.
|
154
|
|
- - Otherwise, if a string starts with `RNFetchBlob-file://` (which can simply 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 request body.
|
155
|
|
-- To send the body as-is, simply use a `Content-Type` header not containing `;BASE64` or `application/octet`.
|
156
|
|
-
|
157
|
|
-> 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'`
|
158
|
|
-
|
159
|
|
-> After 0.9.4, we disabled `Chunked` transfer encoding by default, if you're going to use it, you should explicitly set header `Transfer-Encoding` to `Chunked`.
|
160
|
|
-
|
161
|
|
-### Download example : Fetch files that needs authorization token
|
162
|
|
-
|
163
|
|
-Most simple way is download to memory and stored as BASE64 encoded string, this is handy when the response data is small.
|
164
|
|
-
|
165
|
|
-```js
|
166
|
|
-
|
167
|
|
-// send http request in a new thread (using native code)
|
168
|
|
-RNFetchBlob.fetch('GET', 'http://www.example.com/images/img1.png', {
|
169
|
|
- Authorization : 'Bearer access-token...',
|
170
|
|
- // more headers ..
|
171
|
|
- })
|
172
|
|
- // when response status code is 200
|
173
|
|
- .then((res) => {
|
174
|
|
- // the conversion is done in native code
|
175
|
|
- let base64Str = res.base64()
|
176
|
|
- // the following conversions are done in js, it's SYNC
|
177
|
|
- let text = res.text()
|
178
|
|
- let json = res.json()
|
179
|
|
-
|
180
|
|
- })
|
181
|
|
- // Status code is not 200
|
182
|
|
- .catch((errorMessage, statusCode) => {
|
183
|
|
- // error handling
|
184
|
|
- })
|
185
|
|
-```
|
186
|
|
-
|
187
|
|
-### Download to storage directly
|
188
|
|
-
|
189
|
|
-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.
|
190
|
|
-
|
191
|
|
-**These files won't be removed automatically, please refer to [Cache File Management](#user-content-cache-file-management)**
|
192
|
|
-
|
193
|
|
-```js
|
194
|
|
-RNFetchBlob
|
195
|
|
- .config({
|
196
|
|
- // add this option that makes response data to be stored as a file,
|
197
|
|
- // this is much more performant.
|
198
|
|
- fileCache : true,
|
199
|
|
- })
|
200
|
|
- .fetch('GET', 'http://www.example.com/file/example.zip', {
|
201
|
|
- some headers ..
|
202
|
|
- })
|
203
|
|
- .then((res) => {
|
204
|
|
- // the temp file path
|
205
|
|
- console.log('The file saved to ', res.path())
|
206
|
|
- })
|
207
|
|
-```
|
208
|
|
-
|
209
|
|
-**Set Temp File Extension**
|
210
|
|
-
|
211
|
|
-Sometimes you might need a file extension for some reason. For example, 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`.
|
212
|
|
-
|
213
|
|
-```js
|
214
|
|
-RNFetchBlob
|
215
|
|
- .config({
|
216
|
|
- fileCache : true,
|
217
|
|
- // by adding this option, the temp files will have a file extension
|
218
|
|
- appendExt : 'png'
|
219
|
|
- })
|
220
|
|
- .fetch('GET', 'http://www.example.com/file/example.zip', {
|
221
|
|
- some headers ..
|
222
|
|
- })
|
223
|
|
- .then((res) => {
|
224
|
|
- // the temp file path with file extension `png`
|
225
|
|
- console.log('The file saved to ', res.path())
|
226
|
|
- // Beware that when using a file path as Image source on Android,
|
227
|
|
- // you must prepend "file://"" before the file path
|
228
|
|
- imageView = <Image source={{ uri : Platform.OS === 'android' ? 'file://' + res.path() : '' + res.path() }}/>
|
229
|
|
- })
|
230
|
|
-```
|
231
|
|
-
|
232
|
|
-**Use Specific File Path**
|
233
|
|
-
|
234
|
|
-If you prefer a specific path rather than randomly generated one, you can use `path` option. We've added [several constants](#user-content-dirs) in v0.5.0 which represents commonly used directories.
|
235
|
|
-
|
236
|
|
-```js
|
237
|
|
-let dirs = RNFetchBlob.fs.dirs
|
238
|
|
-RNFetchBlob
|
239
|
|
-.config({
|
240
|
|
- // response data will be saved to this path if it has access right.
|
241
|
|
- path : dirs.DocumentDir + '/path-to-file.anything'
|
242
|
|
-})
|
243
|
|
-.fetch('GET', 'http://www.example.com/file/example.zip', {
|
244
|
|
- //some headers ..
|
245
|
|
-})
|
246
|
|
-.then((res) => {
|
247
|
|
- // the path should be dirs.DocumentDir + 'path-to-file.anything'
|
248
|
|
- console.log('The file saved to ', res.path())
|
249
|
|
-})
|
250
|
|
-```
|
251
|
|
-
|
252
|
|
-**These files won't be removed automatically, please refer to [Cache File Management](#user-content-cache-file-management)**
|
253
|
|
-
|
254
|
|
-#### Upload example : Dropbox [files-upload](https://www.dropbox.com/developers/documentation/http/documentation#files-upload) API
|
255
|
|
-
|
256
|
|
-`react-native-fetch-blob` will convert the base64 string in `body` to binary format using native API, this process will be done in a separated thread, so it won't block your GUI.
|
257
|
|
-
|
258
|
|
-```js
|
259
|
|
-
|
260
|
|
-RNFetchBlob.fetch('POST', 'https://content.dropboxapi.com/2/files/upload', {
|
261
|
|
- Authorization : "Bearer access-token...",
|
262
|
|
- 'Dropbox-API-Arg': JSON.stringify({
|
263
|
|
- path : '/img-from-react-native.png',
|
264
|
|
- mode : 'add',
|
265
|
|
- autorename : true,
|
266
|
|
- mute : false
|
267
|
|
- }),
|
268
|
|
- 'Content-Type' : 'application/octet-stream',
|
269
|
|
- // here's the body you're going to send, should be a BASE64 encoded string
|
270
|
|
- // (you can use "base64"(refer to the library 'mathiasbynens/base64') APIs to make one).
|
271
|
|
- // The data will be converted to "byte array"(say, blob) before request sent.
|
272
|
|
- }, base64ImageString)
|
273
|
|
- .then((res) => {
|
274
|
|
- console.log(res.text())
|
275
|
|
- })
|
276
|
|
- .catch((err) => {
|
277
|
|
- // error handling ..
|
278
|
|
- })
|
279
|
|
-```
|
280
|
|
-
|
281
|
|
-### Upload a file from storage
|
282
|
|
-
|
283
|
|
-If you're going to use a `file` as request body, just wrap the path with `wrap` API.
|
284
|
|
-
|
285
|
|
-```js
|
286
|
|
-RNFetchBlob.fetch('POST', 'https://content.dropboxapi.com/2/files/upload', {
|
287
|
|
- // dropbox upload headers
|
288
|
|
- Authorization : "Bearer access-token...",
|
289
|
|
- 'Dropbox-API-Arg': JSON.stringify({
|
290
|
|
- path : '/img-from-react-native.png',
|
291
|
|
- mode : 'add',
|
292
|
|
- autorename : true,
|
293
|
|
- mute : false
|
294
|
|
- }),
|
295
|
|
- 'Content-Type' : 'application/octet-stream',
|
296
|
|
- // Change BASE64 encoded data to a file path with prefix `RNFetchBlob-file://`.
|
297
|
|
- // Or simply wrap the file path with RNFetchBlob.wrap().
|
298
|
|
- }, RNFetchBlob.wrap(PATH_TO_THE_FILE))
|
299
|
|
- .then((res) => {
|
300
|
|
- console.log(res.text())
|
301
|
|
- })
|
302
|
|
- .catch((err) => {
|
303
|
|
- // error handling ..
|
304
|
|
- })
|
305
|
|
-```
|
306
|
|
-
|
307
|
|
-### Multipart/form-data example : Post form data with file and data
|
308
|
|
-
|
309
|
|
-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).
|
310
|
|
-
|
311
|
|
-Elements have property `filename` will be transformed into binary format, otherwise it turns into utf8 string.
|
312
|
|
-
|
313
|
|
-```js
|
314
|
|
-
|
315
|
|
- RNFetchBlob.fetch('POST', 'http://www.example.com/upload-form', {
|
316
|
|
- Authorization : "Bearer access-token",
|
317
|
|
- otherHeader : "foo",
|
318
|
|
- 'Content-Type' : 'multipart/form-data',
|
319
|
|
- }, [
|
320
|
|
- // element with property `filename` will be transformed into `file` in form data
|
321
|
|
- { name : 'avatar', filename : 'avatar.png', data: binaryDataInBase64},
|
322
|
|
- // custom content type
|
323
|
|
- { name : 'avatar-png', filename : 'avatar-png.png', type:'image/png', data: binaryDataInBase64},
|
324
|
|
- // part file from storage
|
325
|
|
- { name : 'avatar-foo', filename : 'avatar-foo.png', type:'image/foo', data: RNFetchBlob.wrap(path_to_a_file)},
|
326
|
|
- // elements without property `filename` will be sent as plain text
|
327
|
|
- { name : 'name', data : 'user'},
|
328
|
|
- { name : 'info', data : JSON.stringify({
|
329
|
|
- mail : 'example@example.com',
|
330
|
|
- tel : '12345678'
|
331
|
|
- })},
|
332
|
|
- ]).then((resp) => {
|
333
|
|
- // ...
|
334
|
|
- }).catch((err) => {
|
335
|
|
- // ...
|
336
|
|
- })
|
337
|
|
-```
|
338
|
|
-
|
339
|
|
-What if you want to append a file to form data ? Just like [upload a file from storage](#user-content-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. But keep in mind when the file is large it's likely crash your app. Please consider use other strategy (see [#94](https://github.com/wkh237/react-native-fetch-blob/issues/94)).
|
340
|
|
-
|
341
|
|
-```js
|
342
|
|
-
|
343
|
|
- RNFetchBlob.fetch('POST', 'http://www.example.com/upload-form', {
|
344
|
|
- Authorization : "Bearer access-token",
|
345
|
|
- otherHeader : "foo",
|
346
|
|
- // this is required, otherwise it won't be process as a multipart/form-data request
|
347
|
|
- 'Content-Type' : 'multipart/form-data',
|
348
|
|
- }, [
|
349
|
|
- // append field data from file path
|
350
|
|
- {
|
351
|
|
- name : 'avatar',
|
352
|
|
- filename : 'avatar.png',
|
353
|
|
- // Change BASE64 encoded data to a file path with prefix `RNFetchBlob-file://`.
|
354
|
|
- // Or simply wrap the file path with RNFetchBlob.wrap().
|
355
|
|
- data: RNFetchBlob.wrap(PATH_TO_THE_FILE)
|
356
|
|
- },
|
357
|
|
- {
|
358
|
|
- name : 'ringtone',
|
359
|
|
- filename : 'ring.mp3',
|
360
|
|
- // use custom MIME type
|
361
|
|
- type : 'application/mp3',
|
362
|
|
- // upload a file from asset is also possible in version >= 0.6.2
|
363
|
|
- data : RNFetchBlob.wrap(RNFetchBlob.fs.asset('default-ringtone.mp3'))
|
364
|
|
- }
|
365
|
|
- // elements without property `filename` will be sent as plain text
|
366
|
|
- { name : 'name', data : 'user'},
|
367
|
|
- { name : 'info', data : JSON.stringify({
|
368
|
|
- mail : 'example@example.com',
|
369
|
|
- tel : '12345678'
|
370
|
|
- })},
|
371
|
|
- ]).then((resp) => {
|
372
|
|
- // ...
|
373
|
|
- }).catch((err) => {
|
374
|
|
- // ...
|
375
|
|
- })
|
376
|
|
-```
|
377
|
|
-
|
378
|
|
-### Upload/Download progress
|
379
|
|
-
|
380
|
|
-In `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.
|
381
|
|
-
|
382
|
|
-```js
|
383
|
|
- RNFetchBlob.fetch('POST', 'http://www.example.com/upload', {
|
384
|
|
- ... some headers,
|
385
|
|
- 'Content-Type' : 'octet-stream'
|
386
|
|
- }, base64DataString)
|
387
|
|
- // listen to upload progress event
|
388
|
|
- .uploadProgress((written, total) => {
|
389
|
|
- console.log('uploaded', written / total)
|
390
|
|
- })
|
391
|
|
- // listen to download progress event
|
392
|
|
- .progress((received, total) => {
|
393
|
|
- console.log('progress', received / total)
|
394
|
|
- })
|
395
|
|
- .then((resp) => {
|
396
|
|
- // ...
|
397
|
|
- })
|
398
|
|
- .catch((err) => {
|
399
|
|
- // ...
|
400
|
|
- })
|
401
|
|
-```
|
402
|
|
-
|
403
|
|
-In `0.9.6`, you can specify an optional first argument which contains `count` and `interval` to limit progress event frequency (this will be done in native context in order to reduce RCT bridge overhead). Notice that `count` argument will not work if the server does not provide response content length.
|
404
|
|
-
|
405
|
|
-
|
406
|
|
-```js
|
407
|
|
- RNFetchBlob.fetch('POST', 'http://www.example.com/upload', {
|
408
|
|
- ... some headers,
|
409
|
|
- 'Content-Type' : 'octet-stream'
|
410
|
|
- }, base64DataString)
|
411
|
|
- // listen to upload progress event, emit every 250ms
|
412
|
|
- .uploadProgress({ interval : 250 },(written, total) => {
|
413
|
|
- console.log('uploaded', written / total)
|
414
|
|
- })
|
415
|
|
- // listen to download progress event, every 10%
|
416
|
|
- .progress({ count : 10 }, (received, total) => {
|
417
|
|
- console.log('progress', received / total)
|
418
|
|
- })
|
419
|
|
- .then((resp) => {
|
420
|
|
- // ...
|
421
|
|
- })
|
422
|
|
- .catch((err) => {
|
423
|
|
- // ...
|
424
|
|
- })
|
425
|
|
-```
|
426
|
|
-
|
427
|
|
-### Cancel Request
|
428
|
|
-
|
429
|
|
-After `0.7.0` it is possible to cancel a HTTP request. When the request cancel, it will definately throws an promise rejection, be sure to catch it.
|
430
|
|
-
|
431
|
|
-```js
|
432
|
|
-let task = RNFetchBlob.fetch('GET', 'http://example.com/file/1')
|
433
|
|
-
|
434
|
|
-task.then(() => { ... })
|
435
|
|
- // handle request cancelled rejection
|
436
|
|
- .catch((err) => {
|
437
|
|
- console.log(err)
|
438
|
|
- })
|
439
|
|
-// cancel the request, the callback function is optional
|
440
|
|
-task.cancel((err) => { ... })
|
441
|
|
-
|
442
|
|
-```
|
443
|
|
-
|
444
|
|
-### RNFetchBlob as Fetch
|
445
|
|
-
|
446
|
|
-0.9.0
|
447
|
|
-
|
448
|
|
-If you have existing code that uses `whatwg-fetch`(the official **fetch**), you don't have to change them after 0.9.0, just use fetch replacement. The difference between Official fetch and fetch replacement is, official fetch uses [whatwg-fetch](https://github.com/github/fetch) js library which wraps XMLHttpRequest polyfill under the hood it's a great library for web developers, however that does not play very well with RN. Our implementation is simply a wrapper of RNFetchBlob.fetch and fs APIs, so you can access all the features we provide.
|
449
|
|
-
|
450
|
|
-[See document and examples](https://github.com/wkh237/react-native-fetch-blob/wiki/Fetch-API#fetch-replacement)
|
451
|
|
-
|
452
|
|
-### Android Media Scanner, and Download Manager Support
|
453
|
|
-
|
454
|
|
-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`.
|
455
|
|
-
|
456
|
|
-**Media Scanner**
|
457
|
|
-
|
458
|
|
-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.
|
459
|
|
-
|
460
|
|
-```js
|
461
|
|
-
|
462
|
|
-RNFetchBlob
|
463
|
|
- .config({
|
464
|
|
- // DCIMDir is in external storage
|
465
|
|
- path : dirs.DCIMDir + '/music.mp3'
|
466
|
|
- })
|
467
|
|
- .fetch('GET', 'http://example.com/music.mp3')
|
468
|
|
- .then((res) => RNFetchBlob.fs.scanFile([ { path : res.path(), mime : 'audio/mpeg' } ]))
|
469
|
|
- .then(() => {
|
470
|
|
- // scan file success
|
471
|
|
- })
|
472
|
|
- .catch((err) => {
|
473
|
|
- // scan file error
|
474
|
|
- })
|
475
|
|
-```
|
476
|
|
-
|
477
|
|
-**Download Manager**
|
478
|
|
-
|
479
|
|
-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.
|
480
|
|
-
|
481
|
|
-<img src="img/download-manager.png" width="256">
|
482
|
|
-
|
483
|
|
-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.
|
484
|
|
-
|
485
|
|
-```js
|
486
|
|
-RNFetchBlob
|
487
|
|
- .config({
|
488
|
|
- addAdnroidDownloads : {
|
489
|
|
- useDownloadManager : true, // <-- this is the only thing required
|
490
|
|
- // Optional, override notification setting (default to true)
|
491
|
|
- notification : false,
|
492
|
|
- // Optional, but recommended since android DownloadManager will fail when
|
493
|
|
- // the url does not contains a file extension, by default the mime type will be text/plain
|
494
|
|
- mime : 'text/plain',
|
495
|
|
- description : 'File downloaded by download manager.'
|
496
|
|
- }
|
497
|
|
- })
|
498
|
|
- .fetch('GET', 'http://example.com/file/somefile')
|
499
|
|
- .then((resp) => {
|
500
|
|
- // the path of downloaded file
|
501
|
|
- resp.path()
|
502
|
|
- })
|
503
|
|
-```
|
504
|
|
-
|
505
|
|
-
|
506
|
|
-**Download Notification and Visibiliy in Download App (Android Only)**
|
507
|
|
-
|
508
|
|
-<img src="img/android-notification1.png" width="256">
|
509
|
|
-<img src="img/android-notification2.png" width="256">
|
510
|
|
-
|
511
|
|
-
|
512
|
|
-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`.
|
513
|
|
-
|
514
|
|
-```js
|
515
|
|
-RNFetchBlob.config({
|
516
|
|
- fileCache : true,
|
517
|
|
- // android only options, these options be a no-op on IOS
|
518
|
|
- addAndroidDownloads : {
|
519
|
|
- // Show notification when response data transmitted
|
520
|
|
- notification : true,
|
521
|
|
- // Title of download notification
|
522
|
|
- title : 'Great ! Download Success ! :O ',
|
523
|
|
- // File description (not notification description)
|
524
|
|
- description : 'An image file.',
|
525
|
|
- mime : 'image/png',
|
526
|
|
- // Make the file scannable by media scanner
|
527
|
|
- meidaScannable : true,
|
528
|
|
- }
|
529
|
|
-})
|
530
|
|
-.fetch('GET', 'http://example.com/image1.png')
|
531
|
|
-.then(...)
|
532
|
|
-```
|
533
|
|
-
|
534
|
|
-**Open Downloaded File with Intent**
|
535
|
|
-
|
536
|
|
-This is a new feature added in `0.9.0`, if you're going to open a file path using official [Linking](https://facebook.github.io/react-native/docs/linking.html) API that might not work as expected, also, if you're going to install an APK in `Downloads` app, that will not work too. As an alternative, you can try `actionViewIntent` API, which will send an ACTION_VIEW intent for you which uses the given `MIME` type.
|
537
|
|
-
|
538
|
|
-Download and install an APK programatically
|
539
|
|
-
|
540
|
|
-```js
|
541
|
|
-
|
542
|
|
-const android = RNFetchBlob.android
|
543
|
|
-
|
544
|
|
-RNFetchBlob.config({
|
545
|
|
- addAndroidDownloads : {
|
546
|
|
- useDownloadManager : true,
|
547
|
|
- title : 'awesome.apk',
|
548
|
|
- description : 'An APK that will be installed',
|
549
|
|
- mime : 'application/vnd.android.package-archive',
|
550
|
|
- mediaScannable : true,
|
551
|
|
- notification : true,
|
552
|
|
- }
|
553
|
|
- })
|
554
|
|
- .fetch('GET', `http://www.example.com/awesome.apk`)
|
555
|
|
- .then((res) => {
|
556
|
|
- android.actionViewIntent(res.path(), 'application/vnd.android.package-archive')
|
557
|
|
- })
|
558
|
|
-```
|
559
|
|
-
|
560
|
|
-Or show an image in image viewer
|
561
|
|
-
|
562
|
|
-```js
|
563
|
|
- android.actionViewIntent(PATH_OF_IMG, 'image/png')
|
564
|
|
-```
|
565
|
|
-
|
566
|
|
-## File System
|
567
|
|
-
|
568
|
|
-### File Access
|
569
|
|
-
|
570
|
|
-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.
|
571
|
|
-
|
572
|
|
-Before start using file APIs, we recommend read [Differences between File Source](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#differences-between-file-source) first.
|
573
|
|
-
|
574
|
|
-File Access APIs
|
575
|
|
-- [asset (0.6.2)](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#assetfilenamestringstring)
|
576
|
|
-- [dirs](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#dirs)
|
577
|
|
-- [createFile](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#createfilepath-data-encodingpromise)
|
578
|
|
-- [writeFile (0.6.0)](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#writefilepathstring-contentstring--array-encodingstring-appendbooleanpromise)
|
579
|
|
-- [appendFile (0.6.0) ](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#appendfilepathstring-contentstring--array-encodingstringpromise)
|
580
|
|
-- [readFile (0.6.0)](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#readfilepath-encodingpromise)
|
581
|
|
-- [readStream](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#readstreampath-encoding-buffersizepromise)
|
582
|
|
-- [writeStream](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#writestreampathstring-encodingstring-appendbooleanpromise)
|
583
|
|
-- [unlink](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#unlinkpathstringpromise)
|
584
|
|
-- [mkdir](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#mkdirpathstringpromise)
|
585
|
|
-- [ls](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#lspathstringpromise)
|
586
|
|
-- [mv](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#mvfromstring-tostringpromise)
|
587
|
|
-- [cp](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#cpsrcstring-deststringpromise)
|
588
|
|
-- [exists](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#existspathstringpromise)
|
589
|
|
-- [isDir](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#isdirpathstringpromise)
|
590
|
|
-- [stat](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#statpathstringpromise)
|
591
|
|
-- [lstat](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#lstatpathstringpromise)
|
592
|
|
-- [scanFile (Android only)](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#scanfilepathstringpromise-androi-only)
|
593
|
|
-
|
594
|
|
-See [File API](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API) for more information
|
595
|
|
-
|
596
|
|
-### File Stream
|
597
|
|
-
|
598
|
|
-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**.
|
599
|
|
-
|
600
|
|
-When calling `readStream` method, you have to `open` the stream, and start to read data. When the file is large, consider use an appropriate `bufferSize` and `interval` to reduce the native event dispatching overhead (see [Performance Tips](#user-content-performance-tips))
|
601
|
|
-
|
602
|
|
-```js
|
603
|
|
-let data = ''
|
604
|
|
-RNFetchBlob.fs.readStream(
|
605
|
|
- // encoding, should be one of `base64`, `utf8`, `ascii`
|
606
|
|
- 'base64',
|
607
|
|
- // file path
|
608
|
|
- PATH_TO_THE_FILE,
|
609
|
|
- // (optional) buffer size, default to 4096 (4095 for BASE64 encoded data)
|
610
|
|
- // when reading file in BASE64 encoding, buffer size must be multiples of 3.
|
611
|
|
- 4095)
|
612
|
|
-.then((ifstream) => {
|
613
|
|
- ifstream.open()
|
614
|
|
- ifstream.onData((chunk) => {
|
615
|
|
- // when encoding is `ascii`, chunk will be an array contains numbers
|
616
|
|
- // otherwise it will be a string
|
617
|
|
- data += chunk
|
618
|
|
- })
|
619
|
|
- ifstream.onError((err) => {
|
620
|
|
- console.log('oops', err)
|
621
|
|
- })
|
622
|
|
- ifstream.onEnd(() => {
|
623
|
|
- <Image source={{ uri : 'data:image/png,base64' + data }}
|
624
|
|
- })
|
625
|
|
-})
|
626
|
|
-```
|
627
|
|
-
|
628
|
|
-When use `writeStream`, the stream is also opened immediately, but you have to `write`, and `close` by yourself.
|
629
|
|
-
|
630
|
|
-```js
|
631
|
|
-RNFetchBlob.fs.writeStream(
|
632
|
|
- PATH_TO_FILE,
|
633
|
|
- // encoding, should be one of `base64`, `utf8`, `ascii`
|
634
|
|
- 'utf8',
|
635
|
|
- // should data append to existing content ?
|
636
|
|
- true)
|
637
|
|
-.then((ofstream) => {
|
638
|
|
- ofstream.write('foo')
|
639
|
|
- ofstream.write('bar')
|
640
|
|
- ofstream.close()
|
641
|
|
-})
|
642
|
|
-
|
643
|
|
-```
|
644
|
|
-
|
645
|
|
-### Cache File Management
|
646
|
|
-
|
647
|
|
-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
|
648
|
|
-
|
649
|
|
-```js
|
650
|
|
-
|
651
|
|
- // remove file using RNFetchblobResponse.flush() object method
|
652
|
|
- RNFetchblob.config({
|
653
|
|
- fileCache : true
|
654
|
|
- })
|
655
|
|
- .fetch('GET', 'http://example.com/download/file')
|
656
|
|
- .then((res) => {
|
657
|
|
- // remove cached file from storage
|
658
|
|
- res.flush()
|
659
|
|
- })
|
660
|
|
-
|
661
|
|
- // remove file by specifying a path
|
662
|
|
- RNFetchBlob.fs.unlink('some-file-path').then(() => {
|
663
|
|
- // ...
|
664
|
|
- })
|
665
|
|
-
|
666
|
|
-```
|
667
|
|
-
|
668
|
|
-You can also grouping requests by using `session` API, and use `dispose` to remove them all when needed.
|
669
|
|
-
|
670
|
|
-```js
|
671
|
|
-
|
672
|
|
- RNFetchblob.config({
|
673
|
|
- fileCache : true
|
674
|
|
- })
|
675
|
|
- .fetch('GET', 'http://example.com/download/file')
|
676
|
|
- .then((res) => {
|
677
|
|
- // set session of a response
|
678
|
|
- res.session('foo')
|
679
|
|
- })
|
680
|
|
-
|
681
|
|
- RNFetchblob.config({
|
682
|
|
- // you can also set session beforehand
|
683
|
|
- session : 'foo'
|
684
|
|
- fileCache : true
|
685
|
|
- })
|
686
|
|
- .fetch('GET', 'http://example.com/download/file')
|
687
|
|
- .then((res) => {
|
688
|
|
- // ...
|
689
|
|
- })
|
690
|
|
-
|
691
|
|
- // or put an existing file path to the session
|
692
|
|
- RNFetchBlob.session('foo').add('some-file-path')
|
693
|
|
- // remove a file path from the session
|
694
|
|
- RNFetchBlob.session('foo').remove('some-file-path')
|
695
|
|
- // list paths of a session
|
696
|
|
- RNFetchBlob.session('foo').list()
|
697
|
|
- // remove all files in a session
|
698
|
|
- RNFetchBlob.session('foo').dispose().then(() => { ... })
|
699
|
|
-
|
700
|
|
-```
|
701
|
|
-
|
702
|
|
-### Transfer Encoding
|
703
|
|
-
|
704
|
|
-After `0.9.4`, the `Chunked` transfer encoding is disabled by default due to some service provoder may not support chunked transfer. To enable it, set `Transfer-Encoding` header to `Chunked`.
|
705
|
|
-
|
706
|
|
-```js
|
707
|
|
-RNFetchBlob.fetch('POST', 'http://example.com/upload', { 'Transfer-Encoding' : 'Chunked' }, bodyData)
|
708
|
|
-```
|
709
|
|
-
|
710
|
|
-### Self-Signed SSL Server
|
711
|
|
-
|
712
|
|
-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`
|
713
|
|
-
|
714
|
|
-```js
|
715
|
|
-RNFetchBlob.config({
|
716
|
|
- trusty : true
|
717
|
|
-})
|
718
|
|
-.then('GET', 'https://mysite.com')
|
719
|
|
-.then((resp) => {
|
720
|
|
- // ...
|
721
|
|
-})
|
722
|
|
-```
|
723
|
|
-
|
724
|
|
-## Web API Polyfills
|
725
|
|
-
|
726
|
|
-After `0.8.0` we've made some [Web API polyfills](https://github.com/wkh237/react-native-fetch-blob/wiki/Web-API-Polyfills-(experimental)) that makes some browser-based library available in RN.
|
727
|
|
-
|
728
|
|
-- Blob
|
729
|
|
-- XMLHttpRequest (Use our implementation if you're going to use it with Blob)
|
730
|
|
-
|
731
|
|
-Here's a [sample app](https://github.com/wkh237/rn-firebase-storage-upload-sample) that uses polyfills to upload files to FireBase.
|
732
|
|
-
|
733
|
|
-## Performance Tips
|
734
|
|
-
|
735
|
|
-**Read Stream Event Overhead**
|
736
|
|
-
|
737
|
|
-When reading data via `fs.readStream` the process seems blocking JS thread when file is large, it's because the default buffer size is quite small (4kb) which result in large amount of events triggered in JS thread, try to increase the buffer size (for example 100kb = 102400) and set a larger interval (which is introduced in 0.9.4 default value is 10ms) to limit the frequency.
|
738
|
|
-
|
739
|
|
-**Reduce RCT Bridge and BASE64 Overhead**
|
740
|
|
-
|
741
|
|
-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.
|
742
|
|
-
|
743
|
|
-<img src="img/performance_1.png" style="width : 100%"/>
|
744
|
|
-
|
745
|
|
-**ASCII Encoding has /terrible Performance**
|
746
|
|
-
|
747
|
|
-Due to the [lack of typed array implementation in JavascriptCore, and limitation of React Native structure](https://github.com/facebook/react-native/issues/1424), to convert data to JS byte array spends lot of time. Use it only when needed, the following chart shows how much time it takes when reading a file with different encoding.
|
748
|
|
-
|
749
|
|
-<img src="img/performance_encoding.png" style="width : 100%"/>
|
750
|
|
-
|
751
|
|
-**Concate and Replacing Files**
|
752
|
|
-
|
753
|
|
-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 done the whole process in native.
|
754
|
|
-
|
755
|
|
-<img src="img/performance_f2f.png" style="width : 100%"/>
|
756
|
|
-
|
757
|
|
-## Changes
|
758
|
|
-
|
759
|
|
-See [release notes](https://github.com/wkh237/react-native-fetch-blob/releases)
|
760
|
|
-
|
761
|
|
-### Development
|
762
|
|
-
|
763
|
|
-If you're interested in hacking this module, check our [development guide](https://github.com/wkh237/react-native-fetch-blob/wiki/Home), there might be some helpful information.
|
764
|
|
-Please feel free to make a PR or file an issue.
|