react-native-blob-util 0.22.0 → 0.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/.eslintrc.js +56 -56
  2. package/LICENSE +21 -21
  3. package/Migration.md +41 -41
  4. package/NuGet.config +11 -11
  5. package/README.md +1109 -1104
  6. package/android/gradle.properties +1 -1
  7. package/android/src/main/AndroidManifest.xml +37 -37
  8. package/android/src/main/java/com/ReactNativeBlobUtil/ReactNativeBlobUtilConfig.java +57 -57
  9. package/android/src/main/java/com/ReactNativeBlobUtil/ReactNativeBlobUtilConst.java +20 -20
  10. package/android/src/main/java/com/ReactNativeBlobUtil/ReactNativeBlobUtilFileTransformer.java +9 -9
  11. package/android/src/main/java/com/ReactNativeBlobUtil/ReactNativeBlobUtilImpl.java +431 -431
  12. package/android/src/main/java/com/ReactNativeBlobUtil/ReactNativeBlobUtilProgressConfig.java +39 -39
  13. package/android/src/main/java/com/ReactNativeBlobUtil/ReactNativeBlobUtilReq.java +1014 -1014
  14. package/android/src/main/java/com/ReactNativeBlobUtil/Response/ReactNativeBlobUtilDefaultResp.java +98 -98
  15. package/android/src/main/java/com/ReactNativeBlobUtil/Response/ReactNativeBlobUtilFileResp.java +166 -166
  16. package/android/src/main/java/com/ReactNativeBlobUtil/Utils/FileDescription.java +19 -19
  17. package/android/src/main/java/com/ReactNativeBlobUtil/Utils/FileProvider.java +4 -4
  18. package/android/src/main/java/com/ReactNativeBlobUtil/Utils/MimeType.java +70 -70
  19. package/android/src/main/java/com/ReactNativeBlobUtil/Utils/PathResolver.java +223 -223
  20. package/android/src/main/java/com/ReactNativeBlobUtil/Utils/Tls12SocketFactory.java +68 -68
  21. package/android/src/main/res/values/strings.xml +3 -3
  22. package/android/src/main/res/xml/provider_paths.xml +12 -12
  23. package/android.js +58 -58
  24. package/class/ReactNativeBlobUtilCanceledFetchError.js +9 -9
  25. package/class/ReactNativeBlobUtilFile.js +5 -5
  26. package/class/ReactNativeBlobUtilReadStream.js +84 -84
  27. package/class/ReactNativeBlobUtilSession.js +68 -68
  28. package/class/ReactNativeBlobUtilWriteStream.js +50 -50
  29. package/class/StatefulPromise.js +7 -7
  30. package/codegenSpecs/NativeBlobUtils.js +86 -86
  31. package/components/Fetch.onPress.js +10 -10
  32. package/components/Fetch.when.js +15 -15
  33. package/fetch.js +350 -350
  34. package/fs.js +480 -480
  35. package/index.js +64 -64
  36. package/index.js.flow +192 -192
  37. package/index.web.js +1 -1
  38. package/ios/PrivacyInfo.xcprivacy +28 -28
  39. package/ios/ReactNativeBlobUtil/ReactNativeBlobUtil.h +55 -55
  40. package/ios/ReactNativeBlobUtil/ReactNativeBlobUtil.mm +992 -992
  41. package/ios/ReactNativeBlobUtil.xcodeproj/project.pbxproj +405 -405
  42. package/ios/ReactNativeBlobUtilConst.h +58 -58
  43. package/ios/ReactNativeBlobUtilConst.mm +47 -47
  44. package/ios/ReactNativeBlobUtilFS.h +108 -108
  45. package/ios/ReactNativeBlobUtilFS.mm +1064 -1064
  46. package/ios/ReactNativeBlobUtilFileTransformer.h +23 -23
  47. package/ios/ReactNativeBlobUtilFileTransformer.mm +20 -20
  48. package/ios/ReactNativeBlobUtilNetwork.h +49 -49
  49. package/ios/ReactNativeBlobUtilNetwork.mm +159 -159
  50. package/ios/ReactNativeBlobUtilProgress.h +32 -32
  51. package/ios/ReactNativeBlobUtilProgress.mm +57 -57
  52. package/ios/ReactNativeBlobUtilReqBuilder.h +37 -37
  53. package/ios/ReactNativeBlobUtilReqBuilder.mm +292 -292
  54. package/ios/ReactNativeBlobUtilRequest.h +48 -48
  55. package/ios/ReactNativeBlobUtilRequest.mm +584 -584
  56. package/ios.js +61 -61
  57. package/json-stream.js +42 -42
  58. package/lib/oboe-browser.js +2703 -2703
  59. package/mediacollection.js +36 -36
  60. package/package.json +68 -68
  61. package/polyfill/Blob.js +362 -362
  62. package/polyfill/Event.js +11 -11
  63. package/polyfill/EventTarget.js +78 -78
  64. package/polyfill/Fetch.js +219 -219
  65. package/polyfill/File.js +27 -27
  66. package/polyfill/FileReader.js +91 -91
  67. package/polyfill/ProgressEvent.js +32 -32
  68. package/polyfill/XMLHttpRequest.js +466 -466
  69. package/polyfill/XMLHttpRequestEventTarget.js +126 -126
  70. package/polyfill/index.js +11 -11
  71. package/react-native-blob-util.podspec +48 -48
  72. package/types.js +69 -69
  73. package/utils/log.js +40 -40
  74. package/utils/unicode.js +7 -7
  75. package/utils/uri.js +33 -33
  76. package/utils/uuid.js +4 -4
  77. package/windows/ExperimentalFeatures.props +33 -33
  78. package/windows/README.md +2 -2
  79. package/windows/ReactNativeBlobUtil/PropertySheet.props +15 -15
  80. package/windows/ReactNativeBlobUtil/ReactNativeBlobUtil.cpp +1836 -1836
  81. package/windows/ReactNativeBlobUtil/ReactNativeBlobUtil.def +3 -3
  82. package/windows/ReactNativeBlobUtil/ReactNativeBlobUtil.h +372 -372
  83. package/windows/ReactNativeBlobUtil/ReactNativeBlobUtil.vcxproj +139 -139
  84. package/windows/ReactNativeBlobUtil/ReactNativeBlobUtil.vcxproj.filters +43 -43
  85. package/windows/ReactNativeBlobUtil/ReactPackageProvider.cpp +20 -20
  86. package/windows/ReactNativeBlobUtil/ReactPackageProvider.h +24 -24
  87. package/windows/ReactNativeBlobUtil/ReactPackageProvider.idl +9 -9
  88. package/windows/ReactNativeBlobUtil/codegen/.clang-format +1 -1
  89. package/windows/ReactNativeBlobUtil/codegen/NativeBlobUtilsDataTypes.g.h +42 -42
  90. package/windows/ReactNativeBlobUtil/codegen/NativeBlobUtilsSpec.g.h +353 -353
  91. package/windows/ReactNativeBlobUtil/packages.config +3 -3
  92. package/windows/ReactNativeBlobUtil/packages.lock.json +59 -59
  93. package/windows/ReactNativeBlobUtil/pch.cpp +1 -1
  94. package/windows/ReactNativeBlobUtil/pch.h +30 -30
  95. package/windows/ReactNativeBlobUtil/resource.h +5 -5
  96. package/windows/ReactNativeBlobUtil/targetver.h +8 -8
  97. package/windows/ReactNativeBlobUtil.sln +43 -43
package/README.md CHANGED
@@ -1,1104 +1,1109 @@
1
- # react-native-blob-util
2
-
3
- [![release](https://img.shields.io/github/release/RonRadtke/react-native-blob-util.svg?style=flat-square)](https://github.com/RonRadtke/react-native-blob-util/releases) [![npm](https://img.shields.io/npm/v/react-native-blob-util.svg?style=flat-square)](https://www.npmjs.com/package/react-native-blob-util) ![](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/RonRadtke/react-native-blob-util/wiki) [![npm](https://img.shields.io/npm/l/react-native-blob-util.svg?maxAge=2592000&style=flat-square)]()
4
-
5
- A project committed to making file access and data transfer easier and more efficient for React Native developers.
6
-
7
- # I forked this project to continue working on it.
8
-
9
- This project is a fork of https://www.npmjs.com/package/rn-fetch-blob which on the other hand is a fork of https://github.com/wkh237/react-native-fetch-blob. Both the original repository and its first fork are not maintained anymore.
10
-
11
- The project will be continued in this repository. React-Native-Blob-Util is fully compatible with RN-Fetch-Blob and React-Native-Fetch-Blob. If you want to support the project feel free to contact me or create a pull request with your feature.
12
-
13
- # Version Compatibility Warning
14
-
15
- react-native-blob-util version **0.17.0** and up is only compatible with react native **0.65** and up.
16
-
17
- react-native-blob-util version **0.10.16** and up is only compatible with react native **0.60** and up.
18
-
19
- ## Features
20
-
21
- - Access and write data to Android Media Store (e.g. Downloads folder on devices > Android 9)
22
- - Transfer data directly from/to storage without BASE64 bridging
23
- - File API supports regular files, Asset files, and CameraRoll files
24
- - Native-to-native file manipulation API, reduce JS bridging performance loss
25
- - File stream support for dealing with large file
26
- - Blob, File, XMLHttpRequest polyfills that make browser-based library available in RN (experimental)
27
- - JSON stream supported base on [Oboe.js](https://github.com/jimhigson/oboe.js/) @jimhigson
28
-
29
- ## React Native New Architecture
30
- With React Native 0.68.0 the switch to enable the new aritechture was introduced.
31
- Starting with version 0.17.0 this library introduces support for the new architecture as well. Of course the old architecture will still be supported.
32
- Further information about it and how to use it you can find here: https://reactnative.dev/docs/next/the-new-architecture/landing-page
33
-
34
- ## Android 10 & 11
35
-
36
- Android 10 introduced scoped storage for apps. Apps no longer can create own directories directly on the external storage or access files outside the apps own directories. With version 0.14.0 support for the media storage is implemented. For more information please see the chapter about the mediastore API.
37
- [test](###android-media-storage)
38
- For more information see: https://developer.android.com/training/data-storage
39
-
40
- ## TOC (visit [Wiki](https://github.com/RonRadtke/react-native-blob-util/wiki) to get the complete documentation)
41
-
42
- * [About](#user-content-about)
43
- * [Installation](#user-content-installation)
44
- * [HTTP Data Transfer](#user-content-http-data-transfer)
45
- * [Regular Request](#user-content-regular-request)
46
- * [Download file](#download-example-fetch-files-that-need-authorization-token)
47
- * [Upload file](#user-content-upload-example--dropbox-files-upload-api)
48
- * [Multipart/form upload](#user-content-multipartform-data-example--post-form-data-with-file-and-data)
49
- * [Upload/Download progress](#user-content-uploaddownload-progress)
50
- * [Cancel HTTP request](#user-content-cancel-request)
51
- * [Android Media Scanner, and Download Manager Support](#user-content-android-media-scanner-and-download-manager-support)
52
- * [Self-Signed SSL Server](#user-content-self-signed-ssl-server)
53
- * [Transfer Encoding](#user-content-transfer-encoding)
54
- * [Drop-in Fetch Replacement](#user-content-drop-in-fetch-replacement)
55
- * [File System](#user-content-file-system)
56
- * [File access](#user-content-file-access)
57
- * [File stream](#user-content-file-stream)
58
- * [Manage cached files](#user-content-cache-file-management)
59
- * [Web API Polyfills](#user-content-web-api-polyfills)
60
- * [Performance Tips](#user-content-performance-tips)
61
- * [API References](https://github.com/RonRadtke/react-native-blob-util/wiki/Fetch-API)
62
- * [Caveats](#user-content-caveats)
63
- * [Development](#user-content-development)
64
-
65
- ## About
66
-
67
- This project was started in the cause of solving issue [facebook/react-native#854](https://github.com/facebook/react-native/issues/854), React Native's lacks of `Blob` implementation which results into problems when transferring binary data.
68
-
69
- 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.
70
-
71
- 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/joltup/rn-firebase-storage-upload-sample)
72
-
73
- ## Installation
74
-
75
- Install package from npm
76
-
77
- ```sh
78
- npm install --save react-native-blob-util
79
- ```
80
-
81
- Or if using CocoaPods, add the pod to your `Podfile`
82
-
83
- ```
84
- pod 'react-native-blob-util',
85
- :path => '../node_modules/react-native-blob-util'
86
- ```
87
-
88
- After `0.10.3` you can install this package directly from Github
89
-
90
- ```sh
91
- # replace <branch_name> with any one of the branches
92
- npm install --save github:RonRadtke/react-native-blob-util#<branch_name>
93
- ```
94
-
95
- **iOS**
96
-
97
- When using the package from npm, run `pod install` from the `ios` directory:
98
-
99
- ```sh
100
- cd ios; pod install; cd ..
101
- ```
102
-
103
- **Okhttp**
104
-
105
- For using the library okhttp3 is required. It's in general included in react-native. The library uses the okhttp version shipped with react-native or used by your app. For very old devices android devices okhttp 3.12 can be used.
106
-
107
- **Manually Link Native Modules**
108
-
109
- If you're using RN 0.60 or higher, manual linking should not be required anymore.
110
-
111
- If automatically linking doesn't work for you, see instructions on [manually linking](https://github.com/RonRadtke/react-native-blob-util/wiki/Manually-Link-Package#index).
112
-
113
- **Automatically Link Native Modules**
114
-
115
- For 0.29.2+ projects, simply link native packages via the following command (note: rnpm has been merged into react-native)
116
-
117
- ```
118
- react-native link react-native-blob-util
119
- ```
120
-
121
- As for projects < 0.29 you need `rnpm` to link native packages
122
-
123
- ```sh
124
- rnpm link
125
- ```
126
-
127
- Optionally, use the following command to add Android permissions to `AndroidManifest.xml` automatically
128
-
129
- ```sh
130
- RNFB_ANDROID_PERMISSIONS=true react-native react-native-blob-util
131
- ```
132
-
133
- pre 0.29 projects
134
-
135
- ```sh
136
- RNFB_ANDROID_PERMISSIONS=true rnpm link
137
- ```
138
-
139
- The link script might not take effect if you have non-default project structure, please visit [the wiki](https://github.com/RonRadtke/react-native-blob-util/wiki/Manually-Link-Package) to link the package manually.
140
-
141
- **Grant Permission to External storage for Android 5.0 or lower**
142
-
143
- The mechanism for granting Android permissions has slightly different since Android 6.0 released, please refer to [Official Document](https://developer.android.com/training/permissions/requesting.html).
144
-
145
- 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`.
146
-
147
- ```diff
148
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
149
- package="com.ReactNativeBlobUtiltest"
150
- android:versionCode="1"
151
- android:versionName="1.0">
152
-
153
- <uses-permission android:name="android.permission.INTERNET" />
154
- <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
155
- + <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
156
- + <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
157
- + <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
158
- ...
159
-
160
- ```
161
-
162
- Also, if you're going to use `Android Download Manager` you have to add this to `AndroidManifest.xml`
163
-
164
- ```diff
165
- <intent-filter>
166
- <action android:name="android.intent.action.MAIN" />
167
- <category android:name="android.intent.category.LAUNCHER" />
168
- + <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
169
- </intent-filter>
170
- ```
171
-
172
- If you are going to use the `wifiOnly` flag, you need to add this to `AndroidManifest.xml`
173
-
174
- ```diff
175
- + <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
176
- ...
177
-
178
- ```
179
-
180
- **Grant Access Permission for Android 6.0**
181
-
182
- 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](https://facebook.github.io/react-native/docs/permissionsandroid).
183
-
184
- ## Usage
185
-
186
- ES6
187
-
188
- The module uses ES6 style export statement, simply use `import` to load the module.
189
-
190
- ```js
191
- import ReactNativeBlobUtil from 'react-native-blob-util'
192
- ```
193
-
194
- ES5
195
-
196
- If you're using ES5 require statement to load the module, please add `default`. See [here](https://github.com/RonRadtke/react-native-blob-util/wiki/Trouble-Shooting#ReactNativeBlobUtilfetch-is-not-a-function) for more detail.
197
-
198
- ```
199
- var ReactNativeBlobUtil = require('react-native-blob-util').default
200
- ```
201
-
202
- ## HTTP Data Transfer
203
-
204
- ### Regular Request
205
-
206
- After `0.8.0` react-native-blob-util 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
207
-
208
- <img src="img/RNFB-Flow-hd.png" style="width : 90%" />
209
-
210
- To sum up:
211
-
212
- - To send a form data, the `Content-Type` header does not matter. When the body is an `Array` we will set proper content type for you.
213
- - To send binary data, you have two choices, use BASE64 encoded string or path points to a file contains the body.
214
- - 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.
215
- - Otherwise, if a string starts with `ReactNativeBlobUtil-file://` (which can simply be done by `ReactNativeBlobUtil.wrap(PATH_TO_THE_FILE)`), it will try to find the data from the URI string after `ReactNativeBlobUtil-file://` and use it as the request body.
216
- - To send the body as-is, simply use a `Content-Type` header not containing `;BASE64` or `application/octet`.
217
-
218
- > 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'`
219
-
220
- > 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`.
221
-
222
- ### Download example: Fetch files that need authorization token
223
-
224
- 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.
225
-
226
- ```js
227
-
228
- // send http request in a new thread (using native code)
229
- ReactNativeBlobUtil.fetch('GET', 'http://www.example.com/images/img1.png', {
230
- Authorization: 'Bearer access-token...',
231
- // more headers ..
232
- })
233
- .then((res) => {
234
- let status = res.info().status;
235
-
236
- if (status == 200) {
237
- // the conversion is done in native code
238
- let base64Str = res.base64()
239
- // the following conversions are done in js, it's SYNC
240
- let text = res.text()
241
- let json = res.json()
242
- }
243
- else {
244
- // handle other status codes
245
- }
246
- })
247
- // Something went wrong:
248
- .catch((errorMessage, statusCode) => {
249
- // error handling
250
- })
251
- ```
252
-
253
- ### Download to storage directly
254
-
255
- 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.
256
-
257
- **These files won't be removed automatically, please refer to [Cache File Management](#user-content-cache-file-management)**
258
-
259
- ```js
260
- ReactNativeBlobUtil
261
- .config({
262
- // add this option that makes response data to be stored as a file,
263
- // this is much more performant.
264
- fileCache: true,
265
- })
266
- .fetch('GET', 'http://www.example.com/file/example.zip', {
267
- //some headers ..
268
- })
269
- .then((res) => {
270
- // the temp file path
271
- console.log('The file saved to ', res.path())
272
- })
273
- ```
274
-
275
- **Set Temp File Extension**
276
-
277
- 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 `config`.
278
-
279
- ```js
280
- ReactNativeBlobUtil
281
- .config({
282
- fileCache: true,
283
- // by adding this option, the temp files will have a file extension
284
- appendExt: 'png'
285
- })
286
- .fetch('GET', 'http://www.example.com/file/example.zip', {
287
- //some headers ..
288
- })
289
- .then((res) => {
290
- // the temp file path with file extension `png`
291
- console.log('The file saved to ', res.path())
292
- // Beware that when using a file path as Image source on Android,
293
- // you must prepend "file://"" before the file path
294
- imageView = <Image source={{uri: Platform.OS === 'android' ? 'file://' + res.path() : '' + res.path()}}/>
295
- })
296
- ```
297
-
298
- **Use Specific File Path**
299
-
300
- If you prefer a particular file path rather than randomly generated one, you can use `path` option. We've added [several constants](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#dirs) in v0.5.0 which represents commonly used directories.
301
-
302
- ```js
303
- let dirs = ReactNativeBlobUtil.fs.dirs
304
- ReactNativeBlobUtil
305
- .config({
306
- // response data will be saved to this path if it has access right.
307
- path: dirs.DocumentDir + '/path-to-file.anything'
308
- })
309
- .fetch('GET', 'http://www.example.com/file/example.zip', {
310
- //some headers ..
311
- })
312
- .then((res) => {
313
- // the path should be dirs.DocumentDir + 'path-to-file.anything'
314
- console.log('The file saved to ', res.path())
315
- })
316
- ```
317
-
318
- **These files won't be removed automatically, please refer to [Cache File Management](#user-content-cache-file-management)**
319
-
320
- **Use File Transformer**
321
-
322
- If you need to perform any processing on the bytes prior to it being written into storage (e.g. if you want it to be encrypted) then you can use `transform` option. NOTE: you will need to set a transformer on the libray (see [Setting a File Transformer](#Setting-A-File-Transformer))
323
-
324
- ```js
325
- ReactNativeBlobUtil
326
- .config({
327
- // response data will be saved to this path if it has access right.
328
- path: dirs.DocumentDir + '/path-to-file.anything',
329
- transform: true
330
- })
331
- .fetch('GET', 'http://www.example.com/file/example.zip', {
332
- //some headers ..
333
- })
334
- .then((res) => {
335
- // the path should be dirs.DocumentDir + 'path-to-file.anything'
336
- console.log('The file saved to ', res.path())
337
- })
338
- ```
339
-
340
- #### Upload example : Dropbox [files-upload](https://www.dropbox.com/developers/documentation/http/documentation#files-upload) API
341
-
342
- `react-native-blob-util` 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.
343
-
344
- ```js
345
-
346
- ReactNativeBlobUtil.fetch('POST', 'https://content.dropboxapi.com/2/files/upload', {
347
- Authorization: "Bearer access-token...",
348
- 'Dropbox-API-Arg': JSON.stringify({
349
- path: '/img-from-react-native.png',
350
- mode: 'add',
351
- autorename: true,
352
- mute: false
353
- }),
354
- 'Content-Type': 'application/octet-stream',
355
- // here's the body you're going to send, should be a BASE64 encoded string
356
- // (you can use "base64"(refer to the library 'mathiasbynens/base64') APIs to make one).
357
- // The data will be converted to "byte array"(say, blob) before request sent.
358
- }, base64ImageString)
359
- .then((res) => {
360
- console.log(res.text())
361
- })
362
- .catch((err) => {
363
- // error handling ..
364
- })
365
- ```
366
-
367
- ### Upload a file from storage
368
-
369
- If you're going to use a `file` as request body, just wrap the path with `wrap` API.
370
-
371
- ```js
372
- ReactNativeBlobUtil.fetch('POST', 'https://content.dropboxapi.com/2/files/upload', {
373
- // dropbox upload headers
374
- Authorization: "Bearer access-token...",
375
- 'Dropbox-API-Arg': JSON.stringify({
376
- path: '/img-from-react-native.png',
377
- mode: 'add',
378
- autorename: true,
379
- mute: false
380
- }),
381
- 'Content-Type': 'application/octet-stream',
382
- // Change BASE64 encoded data to a file path with prefix `ReactNativeBlobUtil-file://`.
383
- // Or simply wrap the file path with ReactNativeBlobUtil.wrap().
384
- }, ReactNativeBlobUtil.wrap(PATH_TO_THE_FILE))
385
- .then((res) => {
386
- console.log(res.text())
387
- })
388
- .catch((err) => {
389
- // error handling ..
390
- })
391
- ```
392
-
393
- ### Multipart/form-data example: Post form data with file and data
394
-
395
- 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).
396
-
397
- Elements have property `filename` will be transformed into binary format, otherwise, it turns into utf8 string.
398
-
399
- ```js
400
-
401
- ReactNativeBlobUtil.fetch('POST', 'http://www.example.com/upload-form', {
402
- Authorization: "Bearer access-token",
403
- otherHeader: "foo",
404
- 'Content-Type': 'multipart/form-data',
405
- }, [
406
- // element with property `filename` will be transformed into `file` in form data
407
- {name: 'avatar', filename: 'avatar.png', data: binaryDataInBase64},
408
- // custom content type
409
- {name: 'avatar-png', filename: 'avatar-png.png', type: 'image/png', data: binaryDataInBase64},
410
- // part file from storage
411
- {name: 'avatar-foo', filename: 'avatar-foo.png', type: 'image/foo', data: ReactNativeBlobUtil.wrap(path_to_a_file)},
412
- // elements without property `filename` will be sent as plain text
413
- {name: 'name', data: 'user'},
414
- {
415
- name: 'info', data: JSON.stringify({
416
- mail: 'example@example.com',
417
- tel: '12345678'
418
- })
419
- },
420
- ]).then((resp) => {
421
- // ...
422
- }).catch((err) => {
423
- // ...
424
- })
425
- ```
426
-
427
- 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 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](https://github.com/joltup/react-native-blob-util/issues/94)).
428
-
429
- ```js
430
-
431
- ReactNativeBlobUtil.fetch('POST', 'http://www.example.com/upload-form', {
432
- Authorization: "Bearer access-token",
433
- otherHeader: "foo",
434
- // this is required, otherwise it won't be process as a multipart/form-data request
435
- 'Content-Type': 'multipart/form-data',
436
- }, [
437
- // append field data from file path
438
- {
439
- name: 'avatar',
440
- filename: 'avatar.png',
441
- // Change BASE64 encoded data to a file path with prefix `ReactNativeBlobUtil-file://`.
442
- // Or simply wrap the file path with ReactNativeBlobUtil.wrap().
443
- data: ReactNativeBlobUtil.wrap(PATH_TO_THE_FILE)
444
- },
445
- {
446
- name: 'ringtone',
447
- filename: 'ring.mp3',
448
- // use custom MIME type
449
- type: 'application/mp3',
450
- // upload a file from asset is also possible in version >= 0.6.2
451
- data: ReactNativeBlobUtil.wrap(ReactNativeBlobUtil.fs.asset('default-ringtone.mp3'))
452
- },
453
- // elements without property `filename` will be sent as plain text
454
- {name: 'name', data: 'user'},
455
- {
456
- name: 'info', data: JSON.stringify({
457
- mail: 'example@example.com',
458
- tel: '12345678'
459
- })
460
- },
461
- ]).then((resp) => {
462
- // ...
463
- }).catch((err) => {
464
- // ...
465
- })
466
- ```
467
-
468
- ### Upload/Download progress
469
-
470
- 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.
471
-
472
- ```js
473
- ReactNativeBlobUtil.fetch('POST', 'http://www.example.com/upload', {
474
- //... some headers,
475
- 'Content-Type': 'octet-stream'
476
- }, base64DataString)
477
- // listen to upload progress event
478
- .uploadProgress((written, total) => {
479
- console.log('uploaded', written / total)
480
- })
481
- // listen to download progress event
482
- .progress((received, total) => {
483
- console.log('progress', received / total)
484
- })
485
- .then((resp) => {
486
- // ...
487
- })
488
- .catch((err) => {
489
- // ...
490
- })
491
- ```
492
-
493
- In `0.9.6`, you can specify an object as the first argument which contains `count` and `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.
494
-
495
- ```js
496
- ReactNativeBlobUtil.fetch('POST', 'http://www.example.com/upload', {
497
- //... some headers,
498
- 'Content-Type': 'octet-stream'
499
- }, base64DataString)
500
- // listen to upload progress event, emit every 250ms
501
- .uploadProgress({interval: 250}, (written, total) => {
502
- console.log('uploaded', written / total)
503
- })
504
- // listen to download progress event, every 10%
505
- .progress({count: 10}, (received, total) => {
506
- console.log('progress', received / total)
507
- })
508
- .then((resp) => {
509
- // ...
510
- })
511
- .catch((err) => {
512
- // ...
513
- })
514
- ```
515
-
516
- ### Cancel Request
517
-
518
- After `0.7.0` it is possible to cancel an HTTP request. Upon cancellation, it throws a promise rejection, be sure to catch it.
519
-
520
- ```js
521
- let task = ReactNativeBlobUtil.fetch('GET', 'http://example.com/file/1')
522
-
523
- task.then(() => { ...
524
- })
525
- // handle request cancelled rejection
526
- .catch((err) => {
527
- console.log(err)
528
- })
529
- // cancel the request, the callback function is optional
530
- task.cancel((err) => { ...
531
- })
532
-
533
- ```
534
-
535
- ### Drop-in Fetch Replacement
536
-
537
- 0.9.0
538
-
539
- If you have existing code that uses `whatwg-fetch`(the official **fetch**), it's not necessary to replace them with `ReactNativeBlobUtil.fetch`, you can simply use our **Fetch Replacement**. The difference between Official them is official fetch uses [whatwg-fetch](https://github.com/github/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 `fetch` and `fs` APIs, so you can access all the features we provided.
540
-
541
- [See document and examples](https://github.com/RonRadtke/react-native-blob-util/wiki/Fetch-API#fetch-replacement)
542
-
543
- ### Android Media Scanner, and Download Manager Support
544
-
545
- 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` or the `Media Storage`.
546
-
547
- **Media Scanner**
548
-
549
- 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.
550
-
551
- ```js
552
-
553
- ReactNativeBlobUtil
554
- .config({
555
- // DCIMDir is in external storage
556
- path: dirs.DCIMDir + '/music.mp3'
557
- })
558
- .fetch('GET', 'http://example.com/music.mp3')
559
- .then((res) => ReactNativeBlobUtil.fs.scanFile([{path: res.path(), mime: 'audio/mpeg'}]))
560
- .then(() => {
561
- // scan file success
562
- })
563
- .catch((err) => {
564
- // scan file error
565
- })
566
- ```
567
-
568
- **Download Manager**
569
-
570
- 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.
571
-
572
- <img src="img/download-manager.png" width="256">
573
-
574
- When using DownloadManager, `fileCache` and `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.
575
-
576
- When download complete, DownloadManager will generate a file path so that you can deal with it.
577
-
578
- ```js
579
- ReactNativeBlobUtil
580
- .config({
581
- addAndroidDownloads: {
582
- useDownloadManager: true, // <-- this is the only thing required
583
- // Optional, override notification setting (default to true)
584
- notification: false,
585
- // Optional, but recommended since android DownloadManager will fail when
586
- // the url does not contains a file extension, by default the mime type will be text/plain
587
- mime: 'text/plain',
588
- description: 'File downloaded by download manager.'
589
- }
590
- })
591
- .fetch('GET', 'http://example.com/file/somefile')
592
- .then((resp) => {
593
- // the path of downloaded file
594
- resp.path()
595
- })
596
- ```
597
-
598
- 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](https://github.com/wkh237/react-native-fetch-blob/issues/236).
599
-
600
- **Download Notification and Visibility in Download App (Android Only)**
601
-
602
- <img src="img/android-notification1.png" width="256">
603
- <img src="img/android-notification2.png" width="256">
604
-
605
-
606
- 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 `config`.
607
-
608
- ```js
609
- ReactNativeBlobUtil.config({
610
- fileCache: true,
611
- // android only options, these options be a no-op on IOS
612
- addAndroidDownloads: {
613
- // Show notification when response data transmitted
614
- notification: true,
615
- // Title of download notification
616
- title: 'Great ! Download Success ! :O ',
617
- // File description (not notification description)
618
- description: 'An image file.',
619
- mime: 'image/png',
620
- // Make the file scannable by media scanner
621
- mediaScannable: true,
622
- }
623
- })
624
- .fetch('GET', 'http://example.com/image1.png')
625
- .then(...)
626
- ```
627
-
628
- **Open Downloaded File with Intent**
629
-
630
- 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 function too. As an alternative, you can try `actionViewIntent` API, which will send an ACTION_VIEW intent for you which uses the given `MIME` type.
631
-
632
- Download and install an APK programmatically
633
-
634
- Note:
635
- be sure to specify the path, do not use the default path, because the permission problem causes the installation to fail, parsing the package fails
636
-
637
- default path: `/data/data/com.android.providers.downloads/cache/xxx.apk` // Will cause parsing of the package to fail,Unable to install APK
638
-
639
- ```js
640
-
641
- const android = ReactNativeBlobUtil.android
642
- const dirs = ReactNativeBlobUtil.fs.dirs;
643
- const apkUrl = "http://www.example.com/awesome.apk";
644
- const fileName = url.substring(url.lastIndexOf('/') + 1);
645
-
646
- ReactNativeBlobUtil.config({
647
- addAndroidDownloads: {
648
- useDownloadManager: true,
649
- path: `${dirs.DownloadDir}/${fileName}`, // <-- Must specify
650
- title: 'awesome.apk',
651
- description: 'An APK that will be installed',
652
- mime: 'application/vnd.android.package-archive',
653
- mediaScannable: true,
654
- notification: true,
655
- }
656
- })
657
- .fetch('GET', `http://www.example.com/awesome.apk`)
658
- .then((res) => {
659
- android.actionViewIntent(res.path(), 'application/vnd.android.package-archive')
660
- })
661
- ```
662
-
663
- Or show an image in image viewer
664
-
665
- ```js
666
- android.actionViewIntent(PATH_OF_IMG, 'image/png')
667
- ```
668
-
669
- ## File System
670
-
671
- ### Android Media Storage
672
-
673
- Android 10 introduced scoped storage and thus new APIs to store files to Documents, Downloads, Music and other collections. Version 0.14.0 introduced an API to access files in the Media Store but also to create and write to new files in the Media Store. In general you only can access files in the Media Store created by your app, or selected by a picker.
674
-
675
- #### CopyToMediaStore
676
-
677
- Copies an existing file from the internal Storage to the Media Store. <br> An example for downloading a file and storing it to the `downloads` collection
678
-
679
- ```js
680
- ReactNativeBlobUtil
681
- .config({
682
- fileCache: true
683
- })
684
- .fetch('GET', 'https://example.de/image.png')
685
- .then(async (res) => {
686
- let result = await ReactNativeBlobUtil.MediaCollection.copyToMediaStore({
687
- name: filename, // name of the file
688
- parentFolder: '', // subdirectory in the Media Store, e.g. HawkIntech/Files to create a folder HawkIntech with a subfolder Files and save the image within this folder
689
- mimeType: 'image/png' // MIME type of the file
690
- },
691
- 'Download', // Media Collection to store the file in ("Audio" | "Image" | "Video" | "Download")
692
- res.path() // Path to the file being copied in the apps own storage
693
- );
694
- });
695
- ```
696
-
697
- This example is taking advantage of the fileCache option to directly store the downloaded file and get a path for. <br>
698
- Currently it's not possible to write data directly from a string recevied by fetch, but only to copy it from a file.
699
-
700
- #### createMediaFile
701
-
702
- Creates a new file in the specified collection without writing any data
703
-
704
- ````js
705
- let path = await ReactNativeBlobUtil.MediaCollection.createMediafile({
706
- name: filename, // name of the file
707
- parentFolder: '', // subdirectory in the Media Store, e.g. HawkIntech/Files to create a folder HawkIntech with a subfolder Files and save the image within this folder
708
- mimeType: 'image/png' // MIME type of the file
709
- }, 'Download'// Media Collection to store the file in ("Audio" | "Image" | "Video" | "Download")
710
- );
711
- ````
712
-
713
- #### writeMediaFile
714
-
715
- Writes data from a file in the apps storage to an existing entry of the Media Store
716
- ````js
717
- await ReactNativeBlobUtil.MediaCollection.writeToMediafile('content://....', // content uri of the entry in the media storage
718
- localpath // path to the file that should be copied
719
- );
720
- ````
721
-
722
- Copies and tranforms data from a file in the apps storage to an existing entry of the Media Store. NOTE: you must set a transformer on the file in order for the transformation to happen (see [Setting a File Transformer](#Setting-A-File-Transformer)).
723
-
724
- ````js
725
- await ReactNativeBlobUtil.MediaCollection.writeToMediafileWithTransform('content://....', // content uri of the entry in the media storage
726
- localpath // path to the file that should be copied
727
- );
728
- ````
729
-
730
- #### copyToInternal
731
- Copies an entry form the media storage to the apps internal storage.
732
- ````js
733
- let destpath = ReactNativeBlobUtil.dirs.CacheDir + '/image.png';
734
- await ReactNativeBlobUtil.MediaCollection.copyToInternal('content://....', // content uri of the entry in the media storage
735
- destpath // path to destination the entry should be copied to
736
- );
737
- ````
738
-
739
- ### File Access
740
-
741
- 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.
742
-
743
- Before start using file APIs, we recommend read [Differences between File Source](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#differences-between-file-source) first.
744
-
745
- File Access APIs
746
-
747
- - [asset (0.6.2)](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#assetfilenamestringstring)
748
- - [dirs](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#dirs)
749
- - [createFile](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#createfilepath-data-encodingpromise)
750
- - [writeFile (0.6.0)](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#writefilepathstring-contentstring--array-encodingstring-appendbooleanpromise)
751
- - writeFileWithTransform
752
- - [appendFile (0.6.0) ](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#appendfilepathstring-contentstring--arraynumber-encodingstring-promisenumber)
753
- - [readFile (0.6.0)](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#readfilepath-encodingpromise)
754
- - readFileWithTransform
755
- - [readStream](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#readstreampath-encoding-buffersize-interval-promisernfbreadstream)
756
- - [hash (0.10.9)](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#hashpath-algorithm-promise)
757
- - [writeStream](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#writestreampathstring-encodingstringpromise)
758
- - [hash](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#hashpath-algorithmpromise)
759
- - [unlink](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#unlinkpathstringpromise)
760
- - [mkdir](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#mkdirpathstringpromise)
761
- - [ls](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#lspathstringpromise)
762
- - [mv](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#mvfromstring-tostringpromise)
763
- - [cp](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#cpsrcstring-deststringpromise)
764
- - [exists](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#existspathstringpromise)
765
- - [isDir](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#isdirpathstringpromise)
766
- - [stat](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#statpathstringpromise)
767
- - [lstat](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#lstatpathstringpromise)
768
- - [scanFile (Android only)](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#scanfilepathstringpromise-androi-only)
769
-
770
- See [File API](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API) for more information
771
-
772
- ### File Stream
773
-
774
- In `v0.5.0` we've added `writeStream` and `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**.
775
-
776
- When calling `readStream` method, you have to `open` the stream, and start to read data. When the file is large, consider using an appropriate `bufferSize` and `interval` to reduce the native event dispatching overhead (see [Performance Tips](#user-content-performance-tips))
777
-
778
- > The file stream event has a default throttle(10ms) and buffer size which preventing it cause too much overhead to main thread, you can also [tweak these values](#user-content-performance-tips).
779
-
780
- ```js
781
- let data = ''
782
- ReactNativeBlobUtil.fs.readStream(
783
- // file path
784
- PATH_TO_THE_FILE,
785
- // encoding, should be one of `base64`, `utf8`, `ascii`
786
- 'base64',
787
- // (optional) buffer size, default to 4096 (4095 for BASE64 encoded data)
788
- // when reading file in BASE64 encoding, buffer size must be multiples of 3.
789
- 4095)
790
- .then((ifstream) => {
791
- ifstream.open()
792
- ifstream.onData((chunk) => {
793
- // when encoding is `ascii`, chunk will be an array contains numbers
794
- // otherwise it will be a string
795
- data += chunk
796
- })
797
- ifstream.onError((err) => {
798
- console.log('oops', err)
799
- })
800
- ifstream.onEnd(() => {
801
- <Image source={{uri: 'data:image/png,base64' + data}}
802
- })
803
- })
804
- ```
805
-
806
- When using `writeStream`, the stream object becomes writable, and you can then perform operations like `write` and `close`.
807
-
808
- Since version 0.10.9 `write()` resolves with the `ReactNativeBlobUtil` instance so you can promise-chain write calls:
809
-
810
- ```js
811
- ReactNativeBlobUtil.fs.writeStream(
812
- PATH_TO_FILE,
813
- // encoding, should be one of `base64`, `utf8`, `ascii`
814
- 'utf8',
815
- // should data append to existing content ?
816
- true
817
- )
818
- .then(ofstream => ofstream.write('foo'))
819
- .then(ofstream => ofstream.write('bar'))
820
- .then(ofstream => ofstream.write('foobar'))
821
- .then(ofstream => ofstream.close())
822
- .catch(console.error)
823
- ```
824
-
825
- or
826
-
827
- ```js
828
- ReactNativeBlobUtil.fs.writeStream(
829
- PATH_TO_FILE,
830
- // encoding, should be one of `base64`, `utf8`, `ascii`
831
- 'utf8',
832
- // should data append to existing content ?
833
- true
834
- )
835
- .then(stream => Promise.all([
836
- stream.write('foo'),
837
- stream.write('bar'),
838
- stream.write('foobar')
839
- ]))
840
- // Use array destructuring to get the stream object from the first item of the array we get from Promise.all()
841
- .then(([stream]) => stream.close())
842
- .catch(console.error)
843
- ```
844
-
845
- You should **NOT** do something like this:
846
-
847
- ```js
848
- ReactNativeBlobUtil.fs.writeStream(
849
- PATH_TO_FILE,
850
- // encoding, should be one of `base64`, `utf8`, `ascii`
851
- 'utf8',
852
- // should data append to existing content ?
853
- true)
854
- .then((ofstream) => {
855
- // BAD IDEA - Don't do this, those writes are unchecked:
856
- ofstream.write('foo')
857
- ofstream.write('bar')
858
- ofstream.close()
859
- })
860
- .catch(console.error) // Cannot catch any write() errors!
861
- ```
862
-
863
- 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.
864
-
865
- ### Cache File Management
866
-
867
- When using `fileCache` or `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
868
-
869
- ```js
870
-
871
- // remove file using ReactNativeBlobUtilResponse.flush() object method
872
- ReactNativeBlobUtil.config({
873
- fileCache: true
874
- })
875
- .fetch('GET', 'http://example.com/download/file')
876
- .then((res) => {
877
- // remove cached file from storage
878
- res.flush()
879
- })
880
-
881
- // remove file by specifying a path
882
- ReactNativeBlobUtil.fs.unlink('some-file-path').then(() => {
883
- // ...
884
- })
885
-
886
- ```
887
-
888
- You can also group requests by using `session` API and use `dispose` to remove them all when needed.
889
-
890
- ```js
891
-
892
- ReactNativeBlobUtil.config({
893
- fileCache: true
894
- })
895
- .fetch('GET', 'http://example.com/download/file')
896
- .then((res) => {
897
- // set session of a response
898
- res.session('foo')
899
- })
900
-
901
- ReactNativeBlobUtil.config({
902
- // you can also set session beforehand
903
- session: 'foo'
904
- fileCache: true
905
- })
906
- .fetch('GET', 'http://example.com/download/file')
907
- .then((res) => {
908
- // ...
909
- })
910
-
911
- // or put an existing file path to the session
912
- ReactNativeBlobUtil.session('foo').add('some-file-path')
913
- // remove a file path from the session
914
- ReactNativeBlobUtil.session('foo').remove('some-file-path')
915
- // list paths of a session
916
- ReactNativeBlobUtil.session('foo').list()
917
- // remove all files in a session
918
- ReactNativeBlobUtil.session('foo').dispose().then(() => { ...
919
- })
920
-
921
- ```
922
-
923
- ### Transfer Encoding
924
-
925
- After `0.9.4`, the `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 `Chunked`.
926
-
927
- ```js
928
- ReactNativeBlobUtil.fetch('POST', 'http://example.com/upload', {'Transfer-Encoding': 'Chunked'}, bodyData)
929
- ```
930
-
931
- ### Self-Signed SSL Server
932
-
933
- By default, react-native-blob-util does NOT allow connection to unknown certification provider since it's dangerous. To connect a server with self-signed certification, you need to add `trusty` to `config` explicitly. This function is available for version >= `0.5.3`
934
- In addition since ``0.16.0`` you'll have to define your own trust manager for android.
935
- ````java
936
- ....
937
- import com.ReactNativeBlobUtil.ReactNativeBlobUtilUtils;
938
- ...
939
-
940
- public class MainApplication extends Application implements ReactApplication {
941
- ...
942
- @Override
943
- public void onCreate() {
944
- ...
945
- ReactNativeBlobUtilUtils.sharedTrustManager = x509TrustManager = new X509TrustManager() {
946
- @Override
947
- public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
948
- }
949
-
950
- @Override
951
- public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
952
- }
953
-
954
- @Override
955
- public java.security.cert.X509Certificate[] getAcceptedIssuers() {
956
- return new java.security.cert.X509Certificate[]{};
957
- }
958
- };
959
- ...
960
- }
961
- ````
962
-
963
- #### Kotlin
964
- ````kotlin
965
- ....
966
- import com.ReactNativeBlobUtil.ReactNativeBlobUtilUtils;
967
- import javax.net.ssl.X509TrustManager
968
- ...
969
-
970
- public class MainApplication extends Application implements ReactApplication {
971
- ...
972
- public void onCreate() {
973
- ...
974
- ReactNativeBlobUtilUtils.sharedTrustManager = object : X509TrustManager {
975
- override fun checkClientTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {}
976
-
977
- override fun checkServerTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {}
978
-
979
- override fun getAcceptedIssuers(): Array<java.security.cert.X509Certificate> {
980
- return arrayOf()
981
- }
982
- };
983
- ...
984
- }
985
- ````
986
-
987
- ```js
988
- ReactNativeBlobUtil.config({
989
- trusty: true
990
- })
991
- .fetch('GET', 'https://mysite.com')
992
- .then((resp) => {
993
- // ...
994
- })
995
- ```
996
-
997
- ### WiFi only requests
998
-
999
- If you wish to only route requests through the Wifi interface, set the below configuration. Note: On Android, the `ACCESS_NETWORK_STATE` permission must be set, and this flag will only work on API version 21 (Lollipop, Android 5.0) or above. APIs below 21 will ignore this flag.
1000
-
1001
- ```js
1002
- ReactNativeBlobUtil.config({
1003
- wifiOnly: true
1004
- })
1005
- .fetch('GET', 'https://mysite.com')
1006
- .then((resp) => {
1007
- // ...
1008
- })
1009
- ```
1010
-
1011
- ### Transform Files
1012
-
1013
- Sometimes you may need the files to be transformed after reading from storage or before writing into storage (eg encryption/decyrption). In order to perform the transformations, use `readFileWithTransform` and `writeFileWithTransform`. NOTE: you must set a transformer on the file in order for the transformation to happen (see [Setting a File Transformer](#Setting-A-File-Transformer)).
1014
-
1015
- ## Web API Polyfills
1016
-
1017
- After `0.8.0` we've made some [Web API polyfills](https://github.com/RonRadtke/react-native-blob-util/wiki/Web-API-Polyfills-(experimental)) that makes some browser-based library available in RN.
1018
-
1019
- - Blob
1020
- - XMLHttpRequest (Use our implementation if you're going to use it with Blob)
1021
-
1022
-
1023
- ## Setting A File Transformer
1024
-
1025
- Setting a file transformer will allow you to specify how data should be transformed whenever the library is writing into storage or reading from storage. A use case for this is if you want the files handled by this library to be encrypted.
1026
-
1027
- If you want to use a file transformer, you must implement an interface defined in:
1028
-
1029
- [ReactNativeBlobUtilFileTransformer.h (iOS)](/ios/ReactNativeBlobUtilFileTransformer.h)
1030
-
1031
- [ReactNativeBlobUtilFileTransformer.java (Android)](/android/src/main/java/com/ReactNativeBlobUtil/ReactNativeBlobUtilFileTransformer.java)
1032
-
1033
- Then you set the File Transformer during app startup
1034
-
1035
- Android:
1036
- ```java
1037
- public class MainApplication extends Application implements ReactApplication {
1038
- ...
1039
- @Override
1040
- public void onCreate() {
1041
- ...
1042
- ReactNativeBlobUtilFileTransformer.sharedFileTransformer = new MyCustomEncryptor();
1043
- ...
1044
- }
1045
- ```
1046
-
1047
- iOS:
1048
- ```m
1049
- @implementation AppDelegate
1050
- ...
1051
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
1052
- {
1053
- ...
1054
- [ReactNativeBlobUtilFileTransformer setFileTransformer: MyCustomEncryptor.new];
1055
- ...
1056
- }
1057
- ```
1058
-
1059
- Here are the places where the transformer would apply
1060
- - Reading a file from the file system
1061
- - Writing a file into the file system
1062
- - Http response is downloaded to storage directly
1063
-
1064
- ## Performance Tips
1065
-
1066
- **Read Stream and Progress Event Overhead**
1067
-
1068
- 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.
1069
-
1070
- **Reduce RCT Bridge and BASE64 Overhead**
1071
-
1072
- 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.
1073
-
1074
- <img src="img/performance_1.png" style="width : 100%"/>
1075
-
1076
- **ASCII Encoding has /terrible Performance**
1077
-
1078
- 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.
1079
-
1080
- <img src="img/performance_encoding.png" style="width : 100%"/>
1081
-
1082
- **Concat and Replacing Files**
1083
-
1084
- 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.
1085
-
1086
- <img src="img/performance_f2f.png" style="width : 100%"/>
1087
-
1088
- ## Caveats
1089
-
1090
- * This library does not urlencode unicode characters in URL automatically, see [#146](https://github.com/wkh237/react-native-fetch-blob/issues/146).
1091
- * When you create a `Blob` , from an existing file, the file **WILL BE REMOVED** if you `close` the blob.
1092
- * If you replaced `window.XMLHttpRequest` for some reason (e.g. make Firebase SDK work), it will also affect how official `fetch` works (basically it should work just fine).
1093
- * When file stream and upload/download progress event slow down your app, consider an upgrade to `0.9.6+`, use [additional arguments](https://github.com/RonRadtke/react-native-blob-util/wiki/Fetch-API#fetchprogressconfig-eventlistenerpromiseReactNativeBlobUtilresponse) to limit its frequency.
1094
- * When passing a file path to the library, remove `file://` prefix.
1095
-
1096
- when you got a problem, have a look at [Trouble Shooting](https://github.com/RonRadtke/react-native-blob-util/wiki/Trouble-Shooting).
1097
-
1098
- ## Changes
1099
-
1100
- See [release notes](https://github.com/RonRadtke/react-native-blob-util/releases)
1101
-
1102
- ### Development
1103
-
1104
- If you're interested in hacking this module, check our [development guide](https://github.com/RonRadtke/react-native-blob-util/wiki/Home), there might be some helpful information. Please feel free to make a PR or file an issue.
1
+ # react-native-blob-util
2
+
3
+ [![release](https://img.shields.io/github/release/RonRadtke/react-native-blob-util.svg?style=flat-square)](https://github.com/RonRadtke/react-native-blob-util/releases) [![npm](https://img.shields.io/npm/v/react-native-blob-util.svg?style=flat-square)](https://www.npmjs.com/package/react-native-blob-util) ![](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/RonRadtke/react-native-blob-util/wiki) [![npm](https://img.shields.io/npm/l/react-native-blob-util.svg?maxAge=2592000&style=flat-square)]()
4
+
5
+ A project committed to making file access and data transfer easier and more efficient for React Native developers.
6
+
7
+ # I forked this project to continue working on it.
8
+
9
+ This project is a fork of https://www.npmjs.com/package/rn-fetch-blob which on the other hand is a fork of https://github.com/wkh237/react-native-fetch-blob. Both the original repository and its first fork are not maintained anymore.
10
+
11
+ The project will be continued in this repository. React-Native-Blob-Util is fully compatible with RN-Fetch-Blob and React-Native-Fetch-Blob. If you want to support the project feel free to contact me or create a pull request with your feature.
12
+
13
+ # Version Compatibility Warning
14
+
15
+ react-native-blob-util version **0.22.0** and up is only compatible with react native **0.76** and up.
16
+ "0.22.0" -> 0.76 RN
17
+ "0.22.1" -> 0.77 RN
18
+ "0.22.2" -> 0.78 RN
19
+
20
+ react-native-blob-util version **0.17.0** and up is only compatible with react native **0.65** and up.
21
+
22
+ react-native-blob-util version **0.10.16** and up is only compatible with react native **0.60** and up.
23
+
24
+ ## Features
25
+
26
+ - Access and write data to Android Media Store (e.g. Downloads folder on devices > Android 9)
27
+ - Transfer data directly from/to storage without BASE64 bridging
28
+ - File API supports regular files, Asset files, and CameraRoll files
29
+ - Native-to-native file manipulation API, reduce JS bridging performance loss
30
+ - File stream support for dealing with large file
31
+ - Blob, File, XMLHttpRequest polyfills that make browser-based library available in RN (experimental)
32
+ - JSON stream supported base on [Oboe.js](https://github.com/jimhigson/oboe.js/) @jimhigson
33
+
34
+ ## React Native New Architecture
35
+ With React Native 0.68.0 the switch to enable the new aritechture was introduced.
36
+ Starting with version 0.17.0 this library introduces support for the new architecture as well. Of course the old architecture will still be supported.
37
+ Further information about it and how to use it you can find here: https://reactnative.dev/docs/next/the-new-architecture/landing-page
38
+
39
+ ## Android 10 & 11
40
+
41
+ Android 10 introduced scoped storage for apps. Apps no longer can create own directories directly on the external storage or access files outside the apps own directories. With version 0.14.0 support for the media storage is implemented. For more information please see the chapter about the mediastore API.
42
+ [test](###android-media-storage)
43
+ For more information see: https://developer.android.com/training/data-storage
44
+
45
+ ## TOC (visit [Wiki](https://github.com/RonRadtke/react-native-blob-util/wiki) to get the complete documentation)
46
+
47
+ * [About](#user-content-about)
48
+ * [Installation](#user-content-installation)
49
+ * [HTTP Data Transfer](#user-content-http-data-transfer)
50
+ * [Regular Request](#user-content-regular-request)
51
+ * [Download file](#download-example-fetch-files-that-need-authorization-token)
52
+ * [Upload file](#user-content-upload-example--dropbox-files-upload-api)
53
+ * [Multipart/form upload](#user-content-multipartform-data-example--post-form-data-with-file-and-data)
54
+ * [Upload/Download progress](#user-content-uploaddownload-progress)
55
+ * [Cancel HTTP request](#user-content-cancel-request)
56
+ * [Android Media Scanner, and Download Manager Support](#user-content-android-media-scanner-and-download-manager-support)
57
+ * [Self-Signed SSL Server](#user-content-self-signed-ssl-server)
58
+ * [Transfer Encoding](#user-content-transfer-encoding)
59
+ * [Drop-in Fetch Replacement](#user-content-drop-in-fetch-replacement)
60
+ * [File System](#user-content-file-system)
61
+ * [File access](#user-content-file-access)
62
+ * [File stream](#user-content-file-stream)
63
+ * [Manage cached files](#user-content-cache-file-management)
64
+ * [Web API Polyfills](#user-content-web-api-polyfills)
65
+ * [Performance Tips](#user-content-performance-tips)
66
+ * [API References](https://github.com/RonRadtke/react-native-blob-util/wiki/Fetch-API)
67
+ * [Caveats](#user-content-caveats)
68
+ * [Development](#user-content-development)
69
+
70
+ ## About
71
+
72
+ This project was started in the cause of solving issue [facebook/react-native#854](https://github.com/facebook/react-native/issues/854), React Native's lacks of `Blob` implementation which results into problems when transferring binary data.
73
+
74
+ 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.
75
+
76
+ 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/joltup/rn-firebase-storage-upload-sample)
77
+
78
+ ## Installation
79
+
80
+ Install package from npm
81
+
82
+ ```sh
83
+ npm install --save react-native-blob-util
84
+ ```
85
+
86
+ Or if using CocoaPods, add the pod to your `Podfile`
87
+
88
+ ```
89
+ pod 'react-native-blob-util',
90
+ :path => '../node_modules/react-native-blob-util'
91
+ ```
92
+
93
+ After `0.10.3` you can install this package directly from Github
94
+
95
+ ```sh
96
+ # replace <branch_name> with any one of the branches
97
+ npm install --save github:RonRadtke/react-native-blob-util#<branch_name>
98
+ ```
99
+
100
+ **iOS**
101
+
102
+ When using the package from npm, run `pod install` from the `ios` directory:
103
+
104
+ ```sh
105
+ cd ios; pod install; cd ..
106
+ ```
107
+
108
+ **Okhttp**
109
+
110
+ For using the library okhttp3 is required. It's in general included in react-native. The library uses the okhttp version shipped with react-native or used by your app. For very old devices android devices okhttp 3.12 can be used.
111
+
112
+ **Manually Link Native Modules**
113
+
114
+ If you're using RN 0.60 or higher, manual linking should not be required anymore.
115
+
116
+ If automatically linking doesn't work for you, see instructions on [manually linking](https://github.com/RonRadtke/react-native-blob-util/wiki/Manually-Link-Package#index).
117
+
118
+ **Automatically Link Native Modules**
119
+
120
+ For 0.29.2+ projects, simply link native packages via the following command (note: rnpm has been merged into react-native)
121
+
122
+ ```
123
+ react-native link react-native-blob-util
124
+ ```
125
+
126
+ As for projects < 0.29 you need `rnpm` to link native packages
127
+
128
+ ```sh
129
+ rnpm link
130
+ ```
131
+
132
+ Optionally, use the following command to add Android permissions to `AndroidManifest.xml` automatically
133
+
134
+ ```sh
135
+ RNFB_ANDROID_PERMISSIONS=true react-native react-native-blob-util
136
+ ```
137
+
138
+ pre 0.29 projects
139
+
140
+ ```sh
141
+ RNFB_ANDROID_PERMISSIONS=true rnpm link
142
+ ```
143
+
144
+ The link script might not take effect if you have non-default project structure, please visit [the wiki](https://github.com/RonRadtke/react-native-blob-util/wiki/Manually-Link-Package) to link the package manually.
145
+
146
+ **Grant Permission to External storage for Android 5.0 or lower**
147
+
148
+ The mechanism for granting Android permissions has slightly different since Android 6.0 released, please refer to [Official Document](https://developer.android.com/training/permissions/requesting.html).
149
+
150
+ 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`.
151
+
152
+ ```diff
153
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android"
154
+ package="com.ReactNativeBlobUtiltest"
155
+ android:versionCode="1"
156
+ android:versionName="1.0">
157
+
158
+ <uses-permission android:name="android.permission.INTERNET" />
159
+ <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
160
+ + <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
161
+ + <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
162
+ + <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
163
+ ...
164
+
165
+ ```
166
+
167
+ Also, if you're going to use `Android Download Manager` you have to add this to `AndroidManifest.xml`
168
+
169
+ ```diff
170
+ <intent-filter>
171
+ <action android:name="android.intent.action.MAIN" />
172
+ <category android:name="android.intent.category.LAUNCHER" />
173
+ + <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
174
+ </intent-filter>
175
+ ```
176
+
177
+ If you are going to use the `wifiOnly` flag, you need to add this to `AndroidManifest.xml`
178
+
179
+ ```diff
180
+ + <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
181
+ ...
182
+
183
+ ```
184
+
185
+ **Grant Access Permission for Android 6.0**
186
+
187
+ 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](https://facebook.github.io/react-native/docs/permissionsandroid).
188
+
189
+ ## Usage
190
+
191
+ ES6
192
+
193
+ The module uses ES6 style export statement, simply use `import` to load the module.
194
+
195
+ ```js
196
+ import ReactNativeBlobUtil from 'react-native-blob-util'
197
+ ```
198
+
199
+ ES5
200
+
201
+ If you're using ES5 require statement to load the module, please add `default`. See [here](https://github.com/RonRadtke/react-native-blob-util/wiki/Trouble-Shooting#ReactNativeBlobUtilfetch-is-not-a-function) for more detail.
202
+
203
+ ```
204
+ var ReactNativeBlobUtil = require('react-native-blob-util').default
205
+ ```
206
+
207
+ ## HTTP Data Transfer
208
+
209
+ ### Regular Request
210
+
211
+ After `0.8.0` react-native-blob-util 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
212
+
213
+ <img src="img/RNFB-Flow-hd.png" style="width : 90%" />
214
+
215
+ To sum up:
216
+
217
+ - To send a form data, the `Content-Type` header does not matter. When the body is an `Array` we will set proper content type for you.
218
+ - To send binary data, you have two choices, use BASE64 encoded string or path points to a file contains the body.
219
+ - 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.
220
+ - Otherwise, if a string starts with `ReactNativeBlobUtil-file://` (which can simply be done by `ReactNativeBlobUtil.wrap(PATH_TO_THE_FILE)`), it will try to find the data from the URI string after `ReactNativeBlobUtil-file://` and use it as the request body.
221
+ - To send the body as-is, simply use a `Content-Type` header not containing `;BASE64` or `application/octet`.
222
+
223
+ > 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'`
224
+
225
+ > 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`.
226
+
227
+ ### Download example: Fetch files that need authorization token
228
+
229
+ 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.
230
+
231
+ ```js
232
+
233
+ // send http request in a new thread (using native code)
234
+ ReactNativeBlobUtil.fetch('GET', 'http://www.example.com/images/img1.png', {
235
+ Authorization: 'Bearer access-token...',
236
+ // more headers ..
237
+ })
238
+ .then((res) => {
239
+ let status = res.info().status;
240
+
241
+ if (status == 200) {
242
+ // the conversion is done in native code
243
+ let base64Str = res.base64()
244
+ // the following conversions are done in js, it's SYNC
245
+ let text = res.text()
246
+ let json = res.json()
247
+ }
248
+ else {
249
+ // handle other status codes
250
+ }
251
+ })
252
+ // Something went wrong:
253
+ .catch((errorMessage, statusCode) => {
254
+ // error handling
255
+ })
256
+ ```
257
+
258
+ ### Download to storage directly
259
+
260
+ 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.
261
+
262
+ **These files won't be removed automatically, please refer to [Cache File Management](#user-content-cache-file-management)**
263
+
264
+ ```js
265
+ ReactNativeBlobUtil
266
+ .config({
267
+ // add this option that makes response data to be stored as a file,
268
+ // this is much more performant.
269
+ fileCache: true,
270
+ })
271
+ .fetch('GET', 'http://www.example.com/file/example.zip', {
272
+ //some headers ..
273
+ })
274
+ .then((res) => {
275
+ // the temp file path
276
+ console.log('The file saved to ', res.path())
277
+ })
278
+ ```
279
+
280
+ **Set Temp File Extension**
281
+
282
+ 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 `config`.
283
+
284
+ ```js
285
+ ReactNativeBlobUtil
286
+ .config({
287
+ fileCache: true,
288
+ // by adding this option, the temp files will have a file extension
289
+ appendExt: 'png'
290
+ })
291
+ .fetch('GET', 'http://www.example.com/file/example.zip', {
292
+ //some headers ..
293
+ })
294
+ .then((res) => {
295
+ // the temp file path with file extension `png`
296
+ console.log('The file saved to ', res.path())
297
+ // Beware that when using a file path as Image source on Android,
298
+ // you must prepend "file://"" before the file path
299
+ imageView = <Image source={{uri: Platform.OS === 'android' ? 'file://' + res.path() : '' + res.path()}}/>
300
+ })
301
+ ```
302
+
303
+ **Use Specific File Path**
304
+
305
+ If you prefer a particular file path rather than randomly generated one, you can use `path` option. We've added [several constants](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#dirs) in v0.5.0 which represents commonly used directories.
306
+
307
+ ```js
308
+ let dirs = ReactNativeBlobUtil.fs.dirs
309
+ ReactNativeBlobUtil
310
+ .config({
311
+ // response data will be saved to this path if it has access right.
312
+ path: dirs.DocumentDir + '/path-to-file.anything'
313
+ })
314
+ .fetch('GET', 'http://www.example.com/file/example.zip', {
315
+ //some headers ..
316
+ })
317
+ .then((res) => {
318
+ // the path should be dirs.DocumentDir + 'path-to-file.anything'
319
+ console.log('The file saved to ', res.path())
320
+ })
321
+ ```
322
+
323
+ **These files won't be removed automatically, please refer to [Cache File Management](#user-content-cache-file-management)**
324
+
325
+ **Use File Transformer**
326
+
327
+ If you need to perform any processing on the bytes prior to it being written into storage (e.g. if you want it to be encrypted) then you can use `transform` option. NOTE: you will need to set a transformer on the libray (see [Setting a File Transformer](#Setting-A-File-Transformer))
328
+
329
+ ```js
330
+ ReactNativeBlobUtil
331
+ .config({
332
+ // response data will be saved to this path if it has access right.
333
+ path: dirs.DocumentDir + '/path-to-file.anything',
334
+ transform: true
335
+ })
336
+ .fetch('GET', 'http://www.example.com/file/example.zip', {
337
+ //some headers ..
338
+ })
339
+ .then((res) => {
340
+ // the path should be dirs.DocumentDir + 'path-to-file.anything'
341
+ console.log('The file saved to ', res.path())
342
+ })
343
+ ```
344
+
345
+ #### Upload example : Dropbox [files-upload](https://www.dropbox.com/developers/documentation/http/documentation#files-upload) API
346
+
347
+ `react-native-blob-util` 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.
348
+
349
+ ```js
350
+
351
+ ReactNativeBlobUtil.fetch('POST', 'https://content.dropboxapi.com/2/files/upload', {
352
+ Authorization: "Bearer access-token...",
353
+ 'Dropbox-API-Arg': JSON.stringify({
354
+ path: '/img-from-react-native.png',
355
+ mode: 'add',
356
+ autorename: true,
357
+ mute: false
358
+ }),
359
+ 'Content-Type': 'application/octet-stream',
360
+ // here's the body you're going to send, should be a BASE64 encoded string
361
+ // (you can use "base64"(refer to the library 'mathiasbynens/base64') APIs to make one).
362
+ // The data will be converted to "byte array"(say, blob) before request sent.
363
+ }, base64ImageString)
364
+ .then((res) => {
365
+ console.log(res.text())
366
+ })
367
+ .catch((err) => {
368
+ // error handling ..
369
+ })
370
+ ```
371
+
372
+ ### Upload a file from storage
373
+
374
+ If you're going to use a `file` as request body, just wrap the path with `wrap` API.
375
+
376
+ ```js
377
+ ReactNativeBlobUtil.fetch('POST', 'https://content.dropboxapi.com/2/files/upload', {
378
+ // dropbox upload headers
379
+ Authorization: "Bearer access-token...",
380
+ 'Dropbox-API-Arg': JSON.stringify({
381
+ path: '/img-from-react-native.png',
382
+ mode: 'add',
383
+ autorename: true,
384
+ mute: false
385
+ }),
386
+ 'Content-Type': 'application/octet-stream',
387
+ // Change BASE64 encoded data to a file path with prefix `ReactNativeBlobUtil-file://`.
388
+ // Or simply wrap the file path with ReactNativeBlobUtil.wrap().
389
+ }, ReactNativeBlobUtil.wrap(PATH_TO_THE_FILE))
390
+ .then((res) => {
391
+ console.log(res.text())
392
+ })
393
+ .catch((err) => {
394
+ // error handling ..
395
+ })
396
+ ```
397
+
398
+ ### Multipart/form-data example: Post form data with file and data
399
+
400
+ 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).
401
+
402
+ Elements have property `filename` will be transformed into binary format, otherwise, it turns into utf8 string.
403
+
404
+ ```js
405
+
406
+ ReactNativeBlobUtil.fetch('POST', 'http://www.example.com/upload-form', {
407
+ Authorization: "Bearer access-token",
408
+ otherHeader: "foo",
409
+ 'Content-Type': 'multipart/form-data',
410
+ }, [
411
+ // element with property `filename` will be transformed into `file` in form data
412
+ {name: 'avatar', filename: 'avatar.png', data: binaryDataInBase64},
413
+ // custom content type
414
+ {name: 'avatar-png', filename: 'avatar-png.png', type: 'image/png', data: binaryDataInBase64},
415
+ // part file from storage
416
+ {name: 'avatar-foo', filename: 'avatar-foo.png', type: 'image/foo', data: ReactNativeBlobUtil.wrap(path_to_a_file)},
417
+ // elements without property `filename` will be sent as plain text
418
+ {name: 'name', data: 'user'},
419
+ {
420
+ name: 'info', data: JSON.stringify({
421
+ mail: 'example@example.com',
422
+ tel: '12345678'
423
+ })
424
+ },
425
+ ]).then((resp) => {
426
+ // ...
427
+ }).catch((err) => {
428
+ // ...
429
+ })
430
+ ```
431
+
432
+ 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 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](https://github.com/joltup/react-native-blob-util/issues/94)).
433
+
434
+ ```js
435
+
436
+ ReactNativeBlobUtil.fetch('POST', 'http://www.example.com/upload-form', {
437
+ Authorization: "Bearer access-token",
438
+ otherHeader: "foo",
439
+ // this is required, otherwise it won't be process as a multipart/form-data request
440
+ 'Content-Type': 'multipart/form-data',
441
+ }, [
442
+ // append field data from file path
443
+ {
444
+ name: 'avatar',
445
+ filename: 'avatar.png',
446
+ // Change BASE64 encoded data to a file path with prefix `ReactNativeBlobUtil-file://`.
447
+ // Or simply wrap the file path with ReactNativeBlobUtil.wrap().
448
+ data: ReactNativeBlobUtil.wrap(PATH_TO_THE_FILE)
449
+ },
450
+ {
451
+ name: 'ringtone',
452
+ filename: 'ring.mp3',
453
+ // use custom MIME type
454
+ type: 'application/mp3',
455
+ // upload a file from asset is also possible in version >= 0.6.2
456
+ data: ReactNativeBlobUtil.wrap(ReactNativeBlobUtil.fs.asset('default-ringtone.mp3'))
457
+ },
458
+ // elements without property `filename` will be sent as plain text
459
+ {name: 'name', data: 'user'},
460
+ {
461
+ name: 'info', data: JSON.stringify({
462
+ mail: 'example@example.com',
463
+ tel: '12345678'
464
+ })
465
+ },
466
+ ]).then((resp) => {
467
+ // ...
468
+ }).catch((err) => {
469
+ // ...
470
+ })
471
+ ```
472
+
473
+ ### Upload/Download progress
474
+
475
+ 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.
476
+
477
+ ```js
478
+ ReactNativeBlobUtil.fetch('POST', 'http://www.example.com/upload', {
479
+ //... some headers,
480
+ 'Content-Type': 'octet-stream'
481
+ }, base64DataString)
482
+ // listen to upload progress event
483
+ .uploadProgress((written, total) => {
484
+ console.log('uploaded', written / total)
485
+ })
486
+ // listen to download progress event
487
+ .progress((received, total) => {
488
+ console.log('progress', received / total)
489
+ })
490
+ .then((resp) => {
491
+ // ...
492
+ })
493
+ .catch((err) => {
494
+ // ...
495
+ })
496
+ ```
497
+
498
+ In `0.9.6`, you can specify an object as the first argument which contains `count` and `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.
499
+
500
+ ```js
501
+ ReactNativeBlobUtil.fetch('POST', 'http://www.example.com/upload', {
502
+ //... some headers,
503
+ 'Content-Type': 'octet-stream'
504
+ }, base64DataString)
505
+ // listen to upload progress event, emit every 250ms
506
+ .uploadProgress({interval: 250}, (written, total) => {
507
+ console.log('uploaded', written / total)
508
+ })
509
+ // listen to download progress event, every 10%
510
+ .progress({count: 10}, (received, total) => {
511
+ console.log('progress', received / total)
512
+ })
513
+ .then((resp) => {
514
+ // ...
515
+ })
516
+ .catch((err) => {
517
+ // ...
518
+ })
519
+ ```
520
+
521
+ ### Cancel Request
522
+
523
+ After `0.7.0` it is possible to cancel an HTTP request. Upon cancellation, it throws a promise rejection, be sure to catch it.
524
+
525
+ ```js
526
+ let task = ReactNativeBlobUtil.fetch('GET', 'http://example.com/file/1')
527
+
528
+ task.then(() => { ...
529
+ })
530
+ // handle request cancelled rejection
531
+ .catch((err) => {
532
+ console.log(err)
533
+ })
534
+ // cancel the request, the callback function is optional
535
+ task.cancel((err) => { ...
536
+ })
537
+
538
+ ```
539
+
540
+ ### Drop-in Fetch Replacement
541
+
542
+ 0.9.0
543
+
544
+ If you have existing code that uses `whatwg-fetch`(the official **fetch**), it's not necessary to replace them with `ReactNativeBlobUtil.fetch`, you can simply use our **Fetch Replacement**. The difference between Official them is official fetch uses [whatwg-fetch](https://github.com/github/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 `fetch` and `fs` APIs, so you can access all the features we provided.
545
+
546
+ [See document and examples](https://github.com/RonRadtke/react-native-blob-util/wiki/Fetch-API#fetch-replacement)
547
+
548
+ ### Android Media Scanner, and Download Manager Support
549
+
550
+ 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` or the `Media Storage`.
551
+
552
+ **Media Scanner**
553
+
554
+ 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.
555
+
556
+ ```js
557
+
558
+ ReactNativeBlobUtil
559
+ .config({
560
+ // DCIMDir is in external storage
561
+ path: dirs.DCIMDir + '/music.mp3'
562
+ })
563
+ .fetch('GET', 'http://example.com/music.mp3')
564
+ .then((res) => ReactNativeBlobUtil.fs.scanFile([{path: res.path(), mime: 'audio/mpeg'}]))
565
+ .then(() => {
566
+ // scan file success
567
+ })
568
+ .catch((err) => {
569
+ // scan file error
570
+ })
571
+ ```
572
+
573
+ **Download Manager**
574
+
575
+ 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.
576
+
577
+ <img src="img/download-manager.png" width="256">
578
+
579
+ When using DownloadManager, `fileCache` and `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.
580
+
581
+ When download complete, DownloadManager will generate a file path so that you can deal with it.
582
+
583
+ ```js
584
+ ReactNativeBlobUtil
585
+ .config({
586
+ addAndroidDownloads: {
587
+ useDownloadManager: true, // <-- this is the only thing required
588
+ // Optional, override notification setting (default to true)
589
+ notification: false,
590
+ // Optional, but recommended since android DownloadManager will fail when
591
+ // the url does not contains a file extension, by default the mime type will be text/plain
592
+ mime: 'text/plain',
593
+ description: 'File downloaded by download manager.'
594
+ }
595
+ })
596
+ .fetch('GET', 'http://example.com/file/somefile')
597
+ .then((resp) => {
598
+ // the path of downloaded file
599
+ resp.path()
600
+ })
601
+ ```
602
+
603
+ 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](https://github.com/wkh237/react-native-fetch-blob/issues/236).
604
+
605
+ **Download Notification and Visibility in Download App (Android Only)**
606
+
607
+ <img src="img/android-notification1.png" width="256">
608
+ <img src="img/android-notification2.png" width="256">
609
+
610
+
611
+ 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 `config`.
612
+
613
+ ```js
614
+ ReactNativeBlobUtil.config({
615
+ fileCache: true,
616
+ // android only options, these options be a no-op on IOS
617
+ addAndroidDownloads: {
618
+ // Show notification when response data transmitted
619
+ notification: true,
620
+ // Title of download notification
621
+ title: 'Great ! Download Success ! :O ',
622
+ // File description (not notification description)
623
+ description: 'An image file.',
624
+ mime: 'image/png',
625
+ // Make the file scannable by media scanner
626
+ mediaScannable: true,
627
+ }
628
+ })
629
+ .fetch('GET', 'http://example.com/image1.png')
630
+ .then(...)
631
+ ```
632
+
633
+ **Open Downloaded File with Intent**
634
+
635
+ 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 function too. As an alternative, you can try `actionViewIntent` API, which will send an ACTION_VIEW intent for you which uses the given `MIME` type.
636
+
637
+ Download and install an APK programmatically
638
+
639
+ Note:
640
+ be sure to specify the path, do not use the default path, because the permission problem causes the installation to fail, parsing the package fails
641
+
642
+ default path: `/data/data/com.android.providers.downloads/cache/xxx.apk` // Will cause parsing of the package to fail,Unable to install APK
643
+
644
+ ```js
645
+
646
+ const android = ReactNativeBlobUtil.android
647
+ const dirs = ReactNativeBlobUtil.fs.dirs;
648
+ const apkUrl = "http://www.example.com/awesome.apk";
649
+ const fileName = url.substring(url.lastIndexOf('/') + 1);
650
+
651
+ ReactNativeBlobUtil.config({
652
+ addAndroidDownloads: {
653
+ useDownloadManager: true,
654
+ path: `${dirs.DownloadDir}/${fileName}`, // <-- Must specify
655
+ title: 'awesome.apk',
656
+ description: 'An APK that will be installed',
657
+ mime: 'application/vnd.android.package-archive',
658
+ mediaScannable: true,
659
+ notification: true,
660
+ }
661
+ })
662
+ .fetch('GET', `http://www.example.com/awesome.apk`)
663
+ .then((res) => {
664
+ android.actionViewIntent(res.path(), 'application/vnd.android.package-archive')
665
+ })
666
+ ```
667
+
668
+ Or show an image in image viewer
669
+
670
+ ```js
671
+ android.actionViewIntent(PATH_OF_IMG, 'image/png')
672
+ ```
673
+
674
+ ## File System
675
+
676
+ ### Android Media Storage
677
+
678
+ Android 10 introduced scoped storage and thus new APIs to store files to Documents, Downloads, Music and other collections. Version 0.14.0 introduced an API to access files in the Media Store but also to create and write to new files in the Media Store. In general you only can access files in the Media Store created by your app, or selected by a picker.
679
+
680
+ #### CopyToMediaStore
681
+
682
+ Copies an existing file from the internal Storage to the Media Store. <br> An example for downloading a file and storing it to the `downloads` collection
683
+
684
+ ```js
685
+ ReactNativeBlobUtil
686
+ .config({
687
+ fileCache: true
688
+ })
689
+ .fetch('GET', 'https://example.de/image.png')
690
+ .then(async (res) => {
691
+ let result = await ReactNativeBlobUtil.MediaCollection.copyToMediaStore({
692
+ name: filename, // name of the file
693
+ parentFolder: '', // subdirectory in the Media Store, e.g. HawkIntech/Files to create a folder HawkIntech with a subfolder Files and save the image within this folder
694
+ mimeType: 'image/png' // MIME type of the file
695
+ },
696
+ 'Download', // Media Collection to store the file in ("Audio" | "Image" | "Video" | "Download")
697
+ res.path() // Path to the file being copied in the apps own storage
698
+ );
699
+ });
700
+ ```
701
+
702
+ This example is taking advantage of the fileCache option to directly store the downloaded file and get a path for. <br>
703
+ Currently it's not possible to write data directly from a string recevied by fetch, but only to copy it from a file.
704
+
705
+ #### createMediaFile
706
+
707
+ Creates a new file in the specified collection without writing any data
708
+
709
+ ````js
710
+ let path = await ReactNativeBlobUtil.MediaCollection.createMediafile({
711
+ name: filename, // name of the file
712
+ parentFolder: '', // subdirectory in the Media Store, e.g. HawkIntech/Files to create a folder HawkIntech with a subfolder Files and save the image within this folder
713
+ mimeType: 'image/png' // MIME type of the file
714
+ }, 'Download'// Media Collection to store the file in ("Audio" | "Image" | "Video" | "Download")
715
+ );
716
+ ````
717
+
718
+ #### writeMediaFile
719
+
720
+ Writes data from a file in the apps storage to an existing entry of the Media Store
721
+ ````js
722
+ await ReactNativeBlobUtil.MediaCollection.writeToMediafile('content://....', // content uri of the entry in the media storage
723
+ localpath // path to the file that should be copied
724
+ );
725
+ ````
726
+
727
+ Copies and tranforms data from a file in the apps storage to an existing entry of the Media Store. NOTE: you must set a transformer on the file in order for the transformation to happen (see [Setting a File Transformer](#Setting-A-File-Transformer)).
728
+
729
+ ````js
730
+ await ReactNativeBlobUtil.MediaCollection.writeToMediafileWithTransform('content://....', // content uri of the entry in the media storage
731
+ localpath // path to the file that should be copied
732
+ );
733
+ ````
734
+
735
+ #### copyToInternal
736
+ Copies an entry form the media storage to the apps internal storage.
737
+ ````js
738
+ let destpath = ReactNativeBlobUtil.dirs.CacheDir + '/image.png';
739
+ await ReactNativeBlobUtil.MediaCollection.copyToInternal('content://....', // content uri of the entry in the media storage
740
+ destpath // path to destination the entry should be copied to
741
+ );
742
+ ````
743
+
744
+ ### File Access
745
+
746
+ 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.
747
+
748
+ Before start using file APIs, we recommend read [Differences between File Source](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#differences-between-file-source) first.
749
+
750
+ File Access APIs
751
+
752
+ - [asset (0.6.2)](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#assetfilenamestringstring)
753
+ - [dirs](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#dirs)
754
+ - [createFile](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#createfilepath-data-encodingpromise)
755
+ - [writeFile (0.6.0)](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#writefilepathstring-contentstring--array-encodingstring-appendbooleanpromise)
756
+ - writeFileWithTransform
757
+ - [appendFile (0.6.0) ](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#appendfilepathstring-contentstring--arraynumber-encodingstring-promisenumber)
758
+ - [readFile (0.6.0)](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#readfilepath-encodingpromise)
759
+ - readFileWithTransform
760
+ - [readStream](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#readstreampath-encoding-buffersize-interval-promisernfbreadstream)
761
+ - [hash (0.10.9)](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#hashpath-algorithm-promise)
762
+ - [writeStream](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#writestreampathstring-encodingstringpromise)
763
+ - [hash](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#hashpath-algorithmpromise)
764
+ - [unlink](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#unlinkpathstringpromise)
765
+ - [mkdir](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#mkdirpathstringpromise)
766
+ - [ls](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#lspathstringpromise)
767
+ - [mv](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#mvfromstring-tostringpromise)
768
+ - [cp](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#cpsrcstring-deststringpromise)
769
+ - [exists](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#existspathstringpromise)
770
+ - [isDir](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#isdirpathstringpromise)
771
+ - [stat](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#statpathstringpromise)
772
+ - [lstat](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#lstatpathstringpromise)
773
+ - [scanFile (Android only)](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API#scanfilepathstringpromise-androi-only)
774
+
775
+ See [File API](https://github.com/RonRadtke/react-native-blob-util/wiki/File-System-Access-API) for more information
776
+
777
+ ### File Stream
778
+
779
+ In `v0.5.0` we've added `writeStream` and `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**.
780
+
781
+ When calling `readStream` method, you have to `open` the stream, and start to read data. When the file is large, consider using an appropriate `bufferSize` and `interval` to reduce the native event dispatching overhead (see [Performance Tips](#user-content-performance-tips))
782
+
783
+ > The file stream event has a default throttle(10ms) and buffer size which preventing it cause too much overhead to main thread, you can also [tweak these values](#user-content-performance-tips).
784
+
785
+ ```js
786
+ let data = ''
787
+ ReactNativeBlobUtil.fs.readStream(
788
+ // file path
789
+ PATH_TO_THE_FILE,
790
+ // encoding, should be one of `base64`, `utf8`, `ascii`
791
+ 'base64',
792
+ // (optional) buffer size, default to 4096 (4095 for BASE64 encoded data)
793
+ // when reading file in BASE64 encoding, buffer size must be multiples of 3.
794
+ 4095)
795
+ .then((ifstream) => {
796
+ ifstream.open()
797
+ ifstream.onData((chunk) => {
798
+ // when encoding is `ascii`, chunk will be an array contains numbers
799
+ // otherwise it will be a string
800
+ data += chunk
801
+ })
802
+ ifstream.onError((err) => {
803
+ console.log('oops', err)
804
+ })
805
+ ifstream.onEnd(() => {
806
+ <Image source={{uri: 'data:image/png,base64' + data}}
807
+ })
808
+ })
809
+ ```
810
+
811
+ When using `writeStream`, the stream object becomes writable, and you can then perform operations like `write` and `close`.
812
+
813
+ Since version 0.10.9 `write()` resolves with the `ReactNativeBlobUtil` instance so you can promise-chain write calls:
814
+
815
+ ```js
816
+ ReactNativeBlobUtil.fs.writeStream(
817
+ PATH_TO_FILE,
818
+ // encoding, should be one of `base64`, `utf8`, `ascii`
819
+ 'utf8',
820
+ // should data append to existing content ?
821
+ true
822
+ )
823
+ .then(ofstream => ofstream.write('foo'))
824
+ .then(ofstream => ofstream.write('bar'))
825
+ .then(ofstream => ofstream.write('foobar'))
826
+ .then(ofstream => ofstream.close())
827
+ .catch(console.error)
828
+ ```
829
+
830
+ or
831
+
832
+ ```js
833
+ ReactNativeBlobUtil.fs.writeStream(
834
+ PATH_TO_FILE,
835
+ // encoding, should be one of `base64`, `utf8`, `ascii`
836
+ 'utf8',
837
+ // should data append to existing content ?
838
+ true
839
+ )
840
+ .then(stream => Promise.all([
841
+ stream.write('foo'),
842
+ stream.write('bar'),
843
+ stream.write('foobar')
844
+ ]))
845
+ // Use array destructuring to get the stream object from the first item of the array we get from Promise.all()
846
+ .then(([stream]) => stream.close())
847
+ .catch(console.error)
848
+ ```
849
+
850
+ You should **NOT** do something like this:
851
+
852
+ ```js
853
+ ReactNativeBlobUtil.fs.writeStream(
854
+ PATH_TO_FILE,
855
+ // encoding, should be one of `base64`, `utf8`, `ascii`
856
+ 'utf8',
857
+ // should data append to existing content ?
858
+ true)
859
+ .then((ofstream) => {
860
+ // BAD IDEA - Don't do this, those writes are unchecked:
861
+ ofstream.write('foo')
862
+ ofstream.write('bar')
863
+ ofstream.close()
864
+ })
865
+ .catch(console.error) // Cannot catch any write() errors!
866
+ ```
867
+
868
+ 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.
869
+
870
+ ### Cache File Management
871
+
872
+ When using `fileCache` or `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
873
+
874
+ ```js
875
+
876
+ // remove file using ReactNativeBlobUtilResponse.flush() object method
877
+ ReactNativeBlobUtil.config({
878
+ fileCache: true
879
+ })
880
+ .fetch('GET', 'http://example.com/download/file')
881
+ .then((res) => {
882
+ // remove cached file from storage
883
+ res.flush()
884
+ })
885
+
886
+ // remove file by specifying a path
887
+ ReactNativeBlobUtil.fs.unlink('some-file-path').then(() => {
888
+ // ...
889
+ })
890
+
891
+ ```
892
+
893
+ You can also group requests by using `session` API and use `dispose` to remove them all when needed.
894
+
895
+ ```js
896
+
897
+ ReactNativeBlobUtil.config({
898
+ fileCache: true
899
+ })
900
+ .fetch('GET', 'http://example.com/download/file')
901
+ .then((res) => {
902
+ // set session of a response
903
+ res.session('foo')
904
+ })
905
+
906
+ ReactNativeBlobUtil.config({
907
+ // you can also set session beforehand
908
+ session: 'foo'
909
+ fileCache: true
910
+ })
911
+ .fetch('GET', 'http://example.com/download/file')
912
+ .then((res) => {
913
+ // ...
914
+ })
915
+
916
+ // or put an existing file path to the session
917
+ ReactNativeBlobUtil.session('foo').add('some-file-path')
918
+ // remove a file path from the session
919
+ ReactNativeBlobUtil.session('foo').remove('some-file-path')
920
+ // list paths of a session
921
+ ReactNativeBlobUtil.session('foo').list()
922
+ // remove all files in a session
923
+ ReactNativeBlobUtil.session('foo').dispose().then(() => { ...
924
+ })
925
+
926
+ ```
927
+
928
+ ### Transfer Encoding
929
+
930
+ After `0.9.4`, the `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 `Chunked`.
931
+
932
+ ```js
933
+ ReactNativeBlobUtil.fetch('POST', 'http://example.com/upload', {'Transfer-Encoding': 'Chunked'}, bodyData)
934
+ ```
935
+
936
+ ### Self-Signed SSL Server
937
+
938
+ By default, react-native-blob-util does NOT allow connection to unknown certification provider since it's dangerous. To connect a server with self-signed certification, you need to add `trusty` to `config` explicitly. This function is available for version >= `0.5.3`
939
+ In addition since ``0.16.0`` you'll have to define your own trust manager for android.
940
+ ````java
941
+ ....
942
+ import com.ReactNativeBlobUtil.ReactNativeBlobUtilUtils;
943
+ ...
944
+
945
+ public class MainApplication extends Application implements ReactApplication {
946
+ ...
947
+ @Override
948
+ public void onCreate() {
949
+ ...
950
+ ReactNativeBlobUtilUtils.sharedTrustManager = x509TrustManager = new X509TrustManager() {
951
+ @Override
952
+ public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
953
+ }
954
+
955
+ @Override
956
+ public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
957
+ }
958
+
959
+ @Override
960
+ public java.security.cert.X509Certificate[] getAcceptedIssuers() {
961
+ return new java.security.cert.X509Certificate[]{};
962
+ }
963
+ };
964
+ ...
965
+ }
966
+ ````
967
+
968
+ #### Kotlin
969
+ ````kotlin
970
+ ....
971
+ import com.ReactNativeBlobUtil.ReactNativeBlobUtilUtils;
972
+ import javax.net.ssl.X509TrustManager
973
+ ...
974
+
975
+ public class MainApplication extends Application implements ReactApplication {
976
+ ...
977
+ public void onCreate() {
978
+ ...
979
+ ReactNativeBlobUtilUtils.sharedTrustManager = object : X509TrustManager {
980
+ override fun checkClientTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {}
981
+
982
+ override fun checkServerTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {}
983
+
984
+ override fun getAcceptedIssuers(): Array<java.security.cert.X509Certificate> {
985
+ return arrayOf()
986
+ }
987
+ };
988
+ ...
989
+ }
990
+ ````
991
+
992
+ ```js
993
+ ReactNativeBlobUtil.config({
994
+ trusty: true
995
+ })
996
+ .fetch('GET', 'https://mysite.com')
997
+ .then((resp) => {
998
+ // ...
999
+ })
1000
+ ```
1001
+
1002
+ ### WiFi only requests
1003
+
1004
+ If you wish to only route requests through the Wifi interface, set the below configuration. Note: On Android, the `ACCESS_NETWORK_STATE` permission must be set, and this flag will only work on API version 21 (Lollipop, Android 5.0) or above. APIs below 21 will ignore this flag.
1005
+
1006
+ ```js
1007
+ ReactNativeBlobUtil.config({
1008
+ wifiOnly: true
1009
+ })
1010
+ .fetch('GET', 'https://mysite.com')
1011
+ .then((resp) => {
1012
+ // ...
1013
+ })
1014
+ ```
1015
+
1016
+ ### Transform Files
1017
+
1018
+ Sometimes you may need the files to be transformed after reading from storage or before writing into storage (eg encryption/decyrption). In order to perform the transformations, use `readFileWithTransform` and `writeFileWithTransform`. NOTE: you must set a transformer on the file in order for the transformation to happen (see [Setting a File Transformer](#Setting-A-File-Transformer)).
1019
+
1020
+ ## Web API Polyfills
1021
+
1022
+ After `0.8.0` we've made some [Web API polyfills](https://github.com/RonRadtke/react-native-blob-util/wiki/Web-API-Polyfills-(experimental)) that makes some browser-based library available in RN.
1023
+
1024
+ - Blob
1025
+ - XMLHttpRequest (Use our implementation if you're going to use it with Blob)
1026
+
1027
+
1028
+ ## Setting A File Transformer
1029
+
1030
+ Setting a file transformer will allow you to specify how data should be transformed whenever the library is writing into storage or reading from storage. A use case for this is if you want the files handled by this library to be encrypted.
1031
+
1032
+ If you want to use a file transformer, you must implement an interface defined in:
1033
+
1034
+ [ReactNativeBlobUtilFileTransformer.h (iOS)](/ios/ReactNativeBlobUtilFileTransformer.h)
1035
+
1036
+ [ReactNativeBlobUtilFileTransformer.java (Android)](/android/src/main/java/com/ReactNativeBlobUtil/ReactNativeBlobUtilFileTransformer.java)
1037
+
1038
+ Then you set the File Transformer during app startup
1039
+
1040
+ Android:
1041
+ ```java
1042
+ public class MainApplication extends Application implements ReactApplication {
1043
+ ...
1044
+ @Override
1045
+ public void onCreate() {
1046
+ ...
1047
+ ReactNativeBlobUtilFileTransformer.sharedFileTransformer = new MyCustomEncryptor();
1048
+ ...
1049
+ }
1050
+ ```
1051
+
1052
+ iOS:
1053
+ ```m
1054
+ @implementation AppDelegate
1055
+ ...
1056
+ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
1057
+ {
1058
+ ...
1059
+ [ReactNativeBlobUtilFileTransformer setFileTransformer: MyCustomEncryptor.new];
1060
+ ...
1061
+ }
1062
+ ```
1063
+
1064
+ Here are the places where the transformer would apply
1065
+ - Reading a file from the file system
1066
+ - Writing a file into the file system
1067
+ - Http response is downloaded to storage directly
1068
+
1069
+ ## Performance Tips
1070
+
1071
+ **Read Stream and Progress Event Overhead**
1072
+
1073
+ 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.
1074
+
1075
+ **Reduce RCT Bridge and BASE64 Overhead**
1076
+
1077
+ 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.
1078
+
1079
+ <img src="img/performance_1.png" style="width : 100%"/>
1080
+
1081
+ **ASCII Encoding has /terrible Performance**
1082
+
1083
+ 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.
1084
+
1085
+ <img src="img/performance_encoding.png" style="width : 100%"/>
1086
+
1087
+ **Concat and Replacing Files**
1088
+
1089
+ 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.
1090
+
1091
+ <img src="img/performance_f2f.png" style="width : 100%"/>
1092
+
1093
+ ## Caveats
1094
+
1095
+ * This library does not urlencode unicode characters in URL automatically, see [#146](https://github.com/wkh237/react-native-fetch-blob/issues/146).
1096
+ * When you create a `Blob` , from an existing file, the file **WILL BE REMOVED** if you `close` the blob.
1097
+ * If you replaced `window.XMLHttpRequest` for some reason (e.g. make Firebase SDK work), it will also affect how official `fetch` works (basically it should work just fine).
1098
+ * When file stream and upload/download progress event slow down your app, consider an upgrade to `0.9.6+`, use [additional arguments](https://github.com/RonRadtke/react-native-blob-util/wiki/Fetch-API#fetchprogressconfig-eventlistenerpromiseReactNativeBlobUtilresponse) to limit its frequency.
1099
+ * When passing a file path to the library, remove `file://` prefix.
1100
+
1101
+ when you got a problem, have a look at [Trouble Shooting](https://github.com/RonRadtke/react-native-blob-util/wiki/Trouble-Shooting).
1102
+
1103
+ ## Changes
1104
+
1105
+ See [release notes](https://github.com/RonRadtke/react-native-blob-util/releases)
1106
+
1107
+ ### Development
1108
+
1109
+ If you're interested in hacking this module, check our [development guide](https://github.com/RonRadtke/react-native-blob-util/wiki/Home), there might be some helpful information. Please feel free to make a PR or file an issue.