Browse Source

#44 wip commit

Ben Hsieh 8 years ago
parent
commit
0db806a5c8

+ 3
- 1
.github/ISSUE_TEMPLATE View File

@@ -1 +1,3 @@
1
-Hi ! Thank you for reporting an issue, but we would like to remind you, we have a trouble shooting page in our wiki. You may need to take a look on that page, perhaps the answer is just right there :p 
1
+Hi ! Thank you for reporting an issue, but we would like to remind you, we have a trouble shooting page in our wiki. You may want to take a look on that page :p 
2
+
3
+* issues which have been tagged as 'needs feedback', will be closed after 2 weeks if receive no feedbacks.

+ 54
- 18
README.md View File

@@ -1,35 +1,38 @@
1
-# react-native-fetch-blob [![release](https://img.shields.io/github/release/wkh237/react-native-fetch-blob.svg?maxAge=86400&style=flat-square)](https://www.npmjs.com/package/react-native-fetch-blob) [![npm](https://img.shields.io/npm/v/react-native-fetch-blob.svg?style=flat-square)](https://www.npmjs.com/package/react-native-fetch-blob) ![](https://img.shields.io/badge/PR-Welcome-brightgreen.svg?style=flat-square) [![npm](https://img.shields.io/npm/l/express.svg?maxAge=2592000&style=flat-square)]() [![npm](https://img.shields.io/badge/inProgress-0.7.0-yellow.svg?style=flat-square)](https://github.com/wkh237/react-native-fetch-blob/milestones)
1
+# react-native-fetch-blob [![release](https://img.shields.io/github/release/wkh237/react-native-fetch-blob.svg?maxAge=86400&style=flat-square)](https://www.npmjs.com/package/react-native-fetch-blob) [![npm](https://img.shields.io/npm/v/react-native-fetch-blob.svg?style=flat-square)](https://www.npmjs.com/package/react-native-fetch-blob) ![](https://img.shields.io/badge/PR-Welcome-brightgreen.svg?style=flat-square) [![npm](https://img.shields.io/npm/l/express.svg?maxAge=2592000&style=flat-square)]()
2 2
 
3
-A module provides upload, download, and files access API. Supports file stream read/write for process large files.
4
-
5
-**Rationale**
6
-
7
-React Native does not support `Blob` object at this moment, which means if you're going to send/receive binary data via `fetch` API, that might not work as you expect. See [facebook/react-native#854](https://github.com/facebook/react-native/issues/854).
8
-
9
-For some use cases, you might get into trouble. For example, displaying an image that requires a specific field in headers (ex. "Authorization : Bearer ...") or body, so you can't just pass the image uri to `Image` component because that will probably returns a 401 response. Or you're going to upload binary data which generated from JS, the server will get an empry body due to [this issue](https://github.com/facebook/react-native/issues/854). With help of APIs provided by this module, you can send HTTP request with any headers, and decide how to handle the response/reqeust data without worry about if it is not supported by `fetch` API. The response data can be just simply converted into BASE64 string, or stored to a file directly so that you can read it by using file access APIs such as readFile, readStream.
10
-
11
-This module was designed to be a substitution of `Blob`, there's a set of APIs including basic file system CRUD method, and file stream reader/writer. Also it has a special `fetch` implementation that supports binary request/response body.
12
-
13
-**Backward Compatible**
14
-
15
-All updates are `backward-compatible` generally you don't have to change existing code unless you're going to use new APIs. But we recommend pre `0.5.0` users consider upgrade the package to latest version, since we have introduced new APIs can either `upload` or `download` files simply using a file path. It's much more memory efficent in some use case. We've also introduced `fs` APIs for access files, and `file stream` API that helps you read/write files (especially for **large ones**), see [Examples](#user-content-recipes) bellow. This module implements native methods, supports both Android (uses awesome native library  [AsyncHttpClient](https://github.com/AsyncHttpClient/async-http-client])) and IOS.
3
+A project committed to make file acess and transfer easier and effiecient for React Native developers.
16 4
 
17 5
 ## TOC
18
-
6
+* [About](#user-content-about)
7
+* [Backward Compatible](#user-content-backward-compatible)
19 8
 * [Installation](#user-content-installation)
20 9
 * [Recipes](#user-content-recipes)
21 10
  * [Download file](#user-content-download-example--fetch-files-that-needs-authorization-token)
22 11
  * [Upload file](#user-content-upload-example--dropbox-files-upload-api)
23 12
  * [Multipart/form upload](#user-content-multipartform-data-example--post-form-data-with-file-and-data)
24 13
  * [Upload/Download progress](#user-content-uploaddownload-progress)
14
+ * [Cancel HTTP request](#user-content-cancel-request)
25 15
  * [Android Media Scanner, and Download Manager Support](#user-content-android-media-scanner-and-download-manager-support)
26 16
  * [File access](#user-content-file-access)
27 17
  * [File stream](#user-content-file-stream)
28 18
  * [Manage cached files](#user-content-cache-file-management)
29 19
  * [Self-Signed SSL Server](#user-content-self-signed-ssl-server)
30 20
 * [API References](https://github.com/wkh237/react-native-fetch-blob/wiki/Fetch-API)
21
+* [Trouble Shooting](https://github.com/wkh237/react-native-fetch-blob/wiki/Trouble-Shooting)
31 22
 * [Development](#user-content-development)
32 23
 
24
+## About
25
+
26
+React Native does not support `Blob` object at this moment, which means if you're going to send/receive binary data via `fetch` API, that might not work as you expect. See [facebook/react-native#854](https://github.com/facebook/react-native/issues/854).
27
+
28
+For some use cases, you might get into trouble. For example, displaying an image that requires a specific field in headers (ex. "Authorization : Bearer ...") or body, so you can't just pass the image uri to `Image` component because that will probably returns a 401 response. Or you're going to upload binary data which generated from JS, the server will get an empry body due to [this issue](https://github.com/facebook/react-native/issues/854). With help of APIs provided by this module, you can send HTTP request with any headers, and decide how to handle the response/reqeust data without worry about if it is not supported by `fetch` API. The response data can be just simply converted into BASE64 string, or stored to a file directly so that you can read it by using file access APIs such as readFile, readStream.
29
+
30
+This module was designed to be a substitution of `Blob`, there's a set of APIs including basic file system CRUD method, and file stream reader/writer. Also it has a special `fetch` implementation that supports binary request/response body.
31
+
32
+## Backward Compatible
33
+
34
+All updates are `backward-compatible` generally you don't have to change existing code unless you're going to use new APIs. But we recommend pre `0.5.0` users consider upgrade the package to latest version, since we have introduced new APIs can either `upload` or `download` files simply using a file path. It's much more memory efficent in some use case. We've also introduced `fs` APIs for access files, and `file stream` API that helps you read/write files (especially for **large ones**), see [Examples](#user-content-recipes) bellow. This module implements native methods, supports both Android (uses same native library as offical RN fetch API [OkHttp](https://github.com/square/okhttp)) and IOS.
35
+
33 36
 ## Installation
34 37
 
35 38
 Install package from npm
@@ -44,9 +47,17 @@ Link package using [rnpm](https://github.com/rnpm/rnpm)
44 47
 rnpm link
45 48
 ```
46 49
 
47
-### For React Native >= 0.29.0 (Android)
50
+### Manually link package
51
+
52
+If rnpm link command failed to link the package automatically, you might try manually link the package.
53
+
54
+Edit add package to`android/settings.gradle`
48 55
 
49
-> If you're using react-native >= `0.29.0`, the package might not be able to link through `rnpm link`, and you might see an error screen similar to [#51](https://github.com/wkh237/react-native-fetch-blob/issues/51), this is because a [a bug in 0.29.0](https://github.com/facebook/react-native/commit/4dabb575b1b311ba541fae7eabbd49f08b5391b3), someone has already fixed it, but the solution does not work on our project, you may have to manually add the package yourself.
56
+```diff
57
+include ':app'      
58
++ include ':react-native-fetch-blob'                                                                                                  
59
++ project(':react-native-fetch-blob').projectDir = new File(rootProject.projectDir,' ../node_modules/react-native-fetch-blob/android')                        
60
+```
50 61
 
51 62
 Add this code to `MainApplication.java`
52 63
 
@@ -63,6 +74,7 @@ protected List<ReactPackage> getPackages() {
63 74
   };
64 75
 ...
65 76
 ```
77
+> If you still having problem on installing this package, please check the [trouble shooting page](https://github.com/wkh237/react-native-fetch-blob/wiki/Trouble-Shooting) or [file an issue](https://github.com/wkh237/react-native-fetch-blob/issues/new)
66 78
 
67 79
 **Grant Permission to External storage for Android 5.0 or lower**
68 80
 
@@ -317,13 +329,18 @@ What if you want to upload a file in some field ? Just like [upload a file from
317 329
 
318 330
 #### Upload/Download progress
319 331
 
320
-In `version >= 0.4.2` it is possible to know the upload/download progress. On Android, only download progress is supported. See [wiki](https://github.com/wkh237/react-native-fetch-blob/wiki/Fetch-API#fetchprogresseventlistenerpromisernfetchblobresponse) for more information.
332
+In `version >= 0.4.2` it is possible to know the upload/download progress. After `0.7.0` IOS and Android upload progress are supported.
321 333
 
322 334
 ```js
323 335
   RNFetchBlob.fetch('POST', 'http://www.example.com/upload', {
324 336
       ... some headers,
325 337
       'Content-Type' : 'octet-stream'
326 338
     }, base64DataString)
339
+    // listen to upload progress event
340
+    .uploadProgress((written, total) => {
341
+        console.log('uploaded', written / total)
342
+    })
343
+    // listen to download progress event
327 344
     .progress((received, total) => {
328 345
         console.log('progress', received / total)
329 346
     })
@@ -335,6 +352,23 @@ In `version >= 0.4.2` it is possible to know the upload/download progress. On An
335 352
     })
336 353
 ```
337 354
 
355
+#### Cancel Request
356
+
357
+After `0.7.0` it is possible to cancel a HTTP request. When the request cancel, it will definately throws an promise rejection, be sure to catch it.
358
+
359
+```js
360
+let task = RNFetchBlob.fetch('GET', 'http://example.com/file/1')
361
+
362
+task.then(() => { ... })
363
+    // handle request cancelled rejection
364
+    .catch((err) => {
365
+        console.log(err)
366
+    })
367
+// cancel the request, the callback function is optional
368
+task.cancel((err) => { ... })
369
+
370
+```
371
+
338 372
 #### Android Media Scanner, and Download Manager Support
339 373
 
340 374
 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`.
@@ -569,6 +603,8 @@ RNFetchBlob.config({
569 603
 
570 604
 | Version | |
571 605
 |---|---|
606
+| 0.7.1 | Fix #57 ios module could not compile on ios version <= 9.3 |
607
+| 0.7.0 | Add support of Android upload progress, and remove AsyncHttpClient dependency from Android native implementation. |
572 608
 | 0.6.4 | Fix rnpm link script. |
573 609
 | 0.6.3 | Fix performance issue on IOS, increase max concurrent request limitation from 1. |
574 610
 | 0.6.2 | Add support of asset file and camera roll files, Support custom MIME type when sending multipart request, thanks @smartt |

+ 1
- 1
package.json View File

@@ -1,6 +1,6 @@
1 1
 {
2 2
   "name": "fetchblob",
3
-  "version": "0.6.4",
3
+  "version": "0.7.1",
4 4
   "private": true,
5 5
   "scripts": {
6 6
     "start": "node node_modules/react-native/local-cli/cli.js start",

+ 70
- 20
src/README.md View File

@@ -1,37 +1,40 @@
1
-# react-native-fetch-blob [![npm](https://img.shields.io/npm/v/react-native-fetch-blob.svg?style=flat-square)](https://www.npmjs.com/package/react-native-fetch-blob) ![](https://img.shields.io/badge/PR-Welcome-brightgreen.svg?style=flat-square) [![npm](https://img.shields.io/npm/l/express.svg?maxAge=2592000&style=flat-square)]() [![npm](https://img.shields.io/badge/inProgress-0.7.0-yellow.svg?style=flat-square)](https://github.com/wkh237/react-native-fetch-blob/milestones)
1
+# react-native-fetch-blob [![release](https://img.shields.io/github/release/wkh237/react-native-fetch-blob.svg?maxAge=86400&style=flat-square)](https://www.npmjs.com/package/react-native-fetch-blob) [![npm](https://img.shields.io/npm/v/react-native-fetch-blob.svg?style=flat-square)](https://www.npmjs.com/package/react-native-fetch-blob) ![](https://img.shields.io/badge/PR-Welcome-brightgreen.svg?style=flat-square) [![npm](https://img.shields.io/npm/l/express.svg?maxAge=2592000&style=flat-square)]() [![npm](https://img.shields.io/badge/inProgress-0.7.0-yellow.svg?style=flat-square)](https://github.com/wkh237/react-native-fetch-blob/milestones)
2 2
 
3 3
 A module provides upload, download, and files access API. Supports file stream read/write for process large files.
4 4
 
5 5
 ## [Please check our github for updated document](https://github.com/wkh237/react-native-fetch-blob)
6 6
 
7
-**Why do we need this**
8
-
9
-React Native does not support `Blob` object at this moment, which means if you're going to send/receive binary data via `fetch` API, that might not work as you expect. See [facebook/react-native#854](https://github.com/facebook/react-native/issues/854).
10
-
11
-For some use cases, you might get into trouble. For example, displaying an image that requires a specific field in headers (ex. "Authorization : Bearer ...") or body, so you can't just pass the image uri to `Image` component because that will probably returns a 401 response. Or you're going to upload binary data which generated from JS, the server will get an empry body due to [this issue](https://github.com/facebook/react-native/issues/854). With help of APIs provided by this module, you can send HTTP request with any headers, and decide how to handle the response/reqeust data without worry about if it is not supported by `fetch` API. The response data can be just simply converted into BASE64 string, or stored to a file directly so that you can read it by using file access APIs such as readFile, readStream.
12
-
13
-This module was designed to be a substitution of `Blob`, there's a set of APIs including basic file system CRUD method, and file stream reader/writer. Also it has a special `fetch` implementation that supports binary request/response body.
14
-
15
-**Backward Compatible**
16
-
17
-All updates are `backward-compatible` generally you don't have to change existing code unless you're going to use new APIs. But we recommend pre `0.5.0` users consider upgrade the package to latest version, since we have introduced new APIs can either `upload` or `download` files simply using a file path. It's much more memory efficent in some use case. We've also introduced `fs` APIs for access files, and `file stream` API that helps you read/write files (especially for **large ones**), see [Examples](#user-content-recipes) bellow. This module implements native methods, supports both Android (uses awesome native library  [AsyncHttpClient](https://github.com/AsyncHttpClient/async-http-client])) and IOS.
18
-
19 7
 ## TOC
20
-
8
+* [About](#user-content-about)
9
+* [Backward Compatible](#user-content-backward-compatible)
21 10
 * [Installation](#user-content-installation)
22 11
 * [Recipes](#user-content-recipes)
23 12
  * [Download file](#user-content-download-example--fetch-files-that-needs-authorization-token)
24 13
  * [Upload file](#user-content-upload-example--dropbox-files-upload-api)
25 14
  * [Multipart/form upload](#user-content-multipartform-data-example--post-form-data-with-file-and-data)
26 15
  * [Upload/Download progress](#user-content-uploaddownload-progress)
16
+ * [Cancel HTTP request](#user-content-cancel-request)
27 17
  * [Android Media Scanner, and Download Manager Support](#user-content-android-media-scanner-and-download-manager-support)
28 18
  * [File access](#user-content-file-access)
29 19
  * [File stream](#user-content-file-stream)
30 20
  * [Manage cached files](#user-content-cache-file-management)
31 21
  * [Self-Signed SSL Server](#user-content-self-signed-ssl-server)
32 22
 * [API References](https://github.com/wkh237/react-native-fetch-blob/wiki/Fetch-API)
23
+* [Trouble Shooting](https://github.com/wkh237/react-native-fetch-blob/wiki/Trouble-Shooting)
33 24
 * [Development](#user-content-development)
34 25
 
26
+## About
27
+
28
+React Native does not support `Blob` object at this moment, which means if you're going to send/receive binary data via `fetch` API, that might not work as you expect. See [facebook/react-native#854](https://github.com/facebook/react-native/issues/854).
29
+
30
+For some use cases, you might get into trouble. For example, displaying an image that requires a specific field in headers (ex. "Authorization : Bearer ...") or body, so you can't just pass the image uri to `Image` component because that will probably returns a 401 response. Or you're going to upload binary data which generated from JS, the server will get an empry body due to [this issue](https://github.com/facebook/react-native/issues/854). With help of APIs provided by this module, you can send HTTP request with any headers, and decide how to handle the response/reqeust data without worry about if it is not supported by `fetch` API. The response data can be just simply converted into BASE64 string, or stored to a file directly so that you can read it by using file access APIs such as readFile, readStream.
31
+
32
+This module was designed to be a substitution of `Blob`, there's a set of APIs including basic file system CRUD method, and file stream reader/writer. Also it has a special `fetch` implementation that supports binary request/response body.
33
+
34
+## Backward Compatible
35
+
36
+All updates are `backward-compatible` generally you don't have to change existing code unless you're going to use new APIs. But we recommend pre `0.5.0` users consider upgrade the package to latest version, since we have introduced new APIs can either `upload` or `download` files simply using a file path. It's much more memory efficent in some use case. We've also introduced `fs` APIs for access files, and `file stream` API that helps you read/write files (especially for **large ones**), see [Examples](#user-content-recipes) bellow. This module implements native methods, supports both Android (uses same native library as offical RN fetch API [OkHttp](https://github.com/square/okhttp)) and IOS.
37
+
35 38
 ## Installation
36 39
 
37 40
 Install package from npm
@@ -46,11 +49,32 @@ Link package using [rnpm](https://github.com/rnpm/rnpm)
46 49
 rnpm link
47 50
 ```
48 51
 
52
+### For React Native >= 0.29.0 (Android)
53
+
54
+> If you're using react-native >= `0.29.0`, the package might not be able to link through `rnpm link`, and you might see an error screen similar to [#51](https://github.com/wkh237/react-native-fetch-blob/issues/51), this is because a [a bug in 0.29.0](https://github.com/facebook/react-native/commit/4dabb575b1b311ba541fae7eabbd49f08b5391b3), someone has already fixed it, but the solution does not work on our project, you may have to manually add the package yourself.
55
+
56
+Add this code to `MainApplication.java`
57
+
58
+```diff
59
+...
60
++ import com.RNFetchBlob.RNFetchBlobPackage;                                                                                 
61
+...
62
+protected List<ReactPackage> getPackages() {
63
+      return Arrays.<ReactPackage>asList(
64
+          new MainReactPackage(),
65
++          new RNFetchBlobPackage()                                                                                         
66
+      );
67
+    }
68
+  };
69
+...
70
+```
71
+> If you still having problem on installing this package, please check the [trouble shooting page](https://github.com/wkh237/react-native-fetch-blob/wiki/Trouble-Shooting) or [file an issue](https://github.com/wkh237/react-native-fetch-blob/issues/new)
72
+
49 73
 **Grant Permission to External storage for Android 5.0 or lower**
50 74
 
51
-Mechanism about granting Android permissions has slightly different since Android 6.0 released, please refer to [Officail Document](https://developer.android.com/training/permissions/requesting.html).
75
+Mechanism about granting Android permissions has slightly different since Android 6.0 released, please refer to [Official Document](https://developer.android.com/training/permissions/requesting.html).
52 76
 
53
-If you're going to access external storage (say, SD card storage) for `Android 5.0` (or lower) devices, you might have to add the following line to `AndroidManifetst.xml`.
77
+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`.
54 78
 
55 79
 ```diff
56 80
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
@@ -112,7 +136,7 @@ RNFetchBlob.fetch('GET', 'http://www.example.com/images/img1.png', {
112 136
 
113 137
 #### Download to storage directly
114 138
 
115
-The simplest way is give a `fileCach` option to config, and set it to `true`. This will let the incoming response data stored in a temporary path **wihout** any file extension.
139
+The simplest way is give a `fileCache` option to config, and set it to `true`. This will let the incoming response data stored in a temporary path **without** any file extension.
116 140
 
117 141
 **These files won't be removed automatically, please refer to [Cache File Management](#user-content-cache-file-management)**
118 142
 
@@ -151,7 +175,7 @@ RNFetchBlob
151 175
     console.log('The file saved to ', res.path())
152 176
     // Beware that when using a file path as Image source on Android,
153 177
     // you must prepend "file://"" before the file path
154
-    imageView = <Image source={{ uri : Platform.OS === 'android' ? 'file://' : '' + res.path() }}/>
178
+    imageView = <Image source={{ uri : Platform.OS === 'android' ? 'file://' + res.path()  : '' + res.path() }}/>
155 179
   })
156 180
 ```
157 181
 
@@ -299,13 +323,18 @@ What if you want to upload a file in some field ? Just like [upload a file from
299 323
 
300 324
 #### Upload/Download progress
301 325
 
302
-In `version >= 0.4.2` it is possible to know the upload/download progress. On Anroid, only download progress is supported. See [wiki](https://github.com/wkh237/react-native-fetch-blob/wiki/Fetch-API#fetchprogresseventlistenerpromisernfetchblobresponse) for more information.
326
+In `version >= 0.4.2` it is possible to know the upload/download progress. After `0.7.0` IOS and Android upload progress are supported.
303 327
 
304 328
 ```js
305 329
   RNFetchBlob.fetch('POST', 'http://www.example.com/upload', {
306 330
       ... some headers,
307 331
       'Content-Type' : 'octet-stream'
308 332
     }, base64DataString)
333
+    // listen to upload progress event
334
+    .uploadProgress((written, total) => {
335
+        console.log('uploaded', written / total)
336
+    })
337
+    // listen to download progress event
309 338
     .progress((received, total) => {
310 339
         console.log('progress', received / total)
311 340
     })
@@ -317,6 +346,23 @@ In `version >= 0.4.2` it is possible to know the upload/download progress. On An
317 346
     })
318 347
 ```
319 348
 
349
+#### Cancel Request
350
+
351
+After `0.7.0` it is possible to cancel a HTTP request. When the request cancel, it will definately throws an promise rejection, be sure to catch it.
352
+
353
+```js
354
+let task = RNFetchBlob.fetch('GET', 'http://example.com/file/1')
355
+
356
+task.then(() => { ... })
357
+    // handle request cancelled rejection
358
+    .catch((err) => {
359
+        console.log(err)
360
+    })
361
+// cancel the request, the callback function is optional
362
+task.cancel((err) => { ... })
363
+
364
+```
365
+
320 366
 #### Android Media Scanner, and Download Manager Support
321 367
 
322 368
 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`.
@@ -403,7 +449,7 @@ RNFetchBlob.config({
403 449
 
404 450
 File access APIs were made when developing `v0.5.0`, which helping us write tests, and was not planned to be a part of this module. However we realized that, it's hard to find a great solution to manage cached files, every one who use this moudle may need these APIs for there cases.
405 451
 
406
-Before get started using file APIs we recommend read [Differences between File Source](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#differences-between-file-source) first.
452
+Before start using file APIs, we recommend read [Differences between File Source](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#differences-between-file-source) first.
407 453
 
408 454
 File Access APIs
409 455
 - [asset (0.6.2)](https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#assetfilenamestringstring)
@@ -551,6 +597,10 @@ RNFetchBlob.config({
551 597
 
552 598
 | Version | |
553 599
 |---|---|
600
+| 0.7.1 | Fix #57 ios module could not compile on ios version <= 9.3 |
601
+| 0.7.0 | Add support of Android upload progress, and remove AsyncHttpClient dependency from Android native implementation. |
602
+| 0.6.4 | Fix rnpm link script. |
603
+| 0.6.3 | Fix performance issue on IOS, increase max concurrent request limitation from 1. |
554 604
 | 0.6.2 | Add support of asset file and camera roll files, Support custom MIME type when sending multipart request, thanks @smartt |
555 605
 | 0.6.1 | Fix #37 progress report API issue on IOS |
556 606
 | 0.6.0 | Add readFile and writeFile API for easier file access, also added Android download manager support. |

+ 6
- 0
src/class/RNFetchBlobFile.js View File

@@ -1,3 +1,9 @@
1
+// Copyright 2016 wkh237@github. All rights reserved.
2
+// Use of this source code is governed by a MIT-style license that can be
3
+// found in the LICENSE file.
4
+// @flow
5
+
6
+
1 7
 import {
2 8
   NativeModules,
3 9
   DeviceEventEmitter,

+ 5
- 0
src/class/RNFetchBlobReadStream.js View File

@@ -1,3 +1,8 @@
1
+// Copyright 2016 wkh237@github. All rights reserved.
2
+// Use of this source code is governed by a MIT-style license that can be
3
+// found in the LICENSE file.
4
+// @flow
5
+
1 6
 import {
2 7
   NativeModules,
3 8
   DeviceEventEmitter,

+ 4
- 4
src/class/RNFetchBlobSession.js View File

@@ -1,7 +1,7 @@
1
-/**
2
- * Session class
3
- * @class RNFetchBlobSession
4
- */
1
+// Copyright 2016 wkh237@github. All rights reserved.
2
+// Use of this source code is governed by a MIT-style license that can be
3
+// found in the LICENSE file.
4
+// @flow
5 5
 
6 6
 import {
7 7
  NativeModules,

+ 5
- 0
src/class/RNFetchBlobWriteStream.js View File

@@ -1,3 +1,8 @@
1
+// Copyright 2016 wkh237@github. All rights reserved.
2
+// Use of this source code is governed by a MIT-style license that can be
3
+// found in the LICENSE file.
4
+// @flow
5
+
1 6
 import {
2 7
  NativeModules,
3 8
  DeviceEventEmitter,

+ 4
- 6
src/fs.js View File

@@ -1,9 +1,7 @@
1
-/**
2
- * @name react-native-fetch-blob-fs
3
- * @author wkh237
4
- * @version 0.7.0
5
- * @flow
6
- */
1
+// Copyright 2016 wkh237@github. All rights reserved.
2
+// Use of this source code is governed by a MIT-style license that can be
3
+// found in the LICENSE file.
4
+// @flow
7 5
 
8 6
 import {
9 7
   NativeModules,

+ 7
- 7
src/index.js View File

@@ -1,9 +1,7 @@
1
-/**
2
- * @name react-native-fetch-blob
3
- * @author wkh237
4
- * @version 0.7.0
5
- * @flow
6
- */
1
+// Copyright 2016 wkh237@github. All rights reserved.
2
+// Use of this source code is governed by a MIT-style license that can be
3
+// found in the LICENSE file.
4
+// @flow
7 5
 
8 6
 import {
9 7
   NativeModules,
@@ -163,6 +161,8 @@ function fetch(...args:any):Promise {
163 161
   }
164 162
   promise.cancel = (fn) => {
165 163
     fn = fn || function(){}
164
+    subscription.remove()
165
+    subscriptionUpload.remove()
166 166
     RNFetchBlob.cancelRequest(taskId, fn)
167 167
   }
168 168
 
@@ -202,7 +202,7 @@ class FetchBlobResponse {
202 202
      */
203 203
     this.blob = (contentType:string, sliceSize:number) => {
204 204
       console.warn('FetchBlobResponse.blob() is deprecated and has no funtionality.')
205
-      return null
205
+      return this
206 206
     }
207 207
     /**
208 208
      * Convert result to text.

+ 1
- 1
src/package.json View File

@@ -1,6 +1,6 @@
1 1
 {
2 2
   "name": "react-native-fetch-blob",
3
-  "version": "0.6.4",
3
+  "version": "0.7.1",
4 4
   "description": "A module provides upload, download, and files access API. Supports file stream read/write for process large files.",
5 5
   "main": "index.js",
6 6
   "scripts": {

+ 4
- 6
src/polyfill/Blob.js View File

@@ -1,9 +1,7 @@
1
-/**
2
- * @author wkh237
3
- * @since 2016/07/18
4
- * @description
5
- * Web API Blob object polyfill.
6
- */
1
+// Copyright 2016 wkh237@github. All rights reserved.
2
+// Use of this source code is governed by a MIT-style license that can be
3
+// found in the LICENSE file.
4
+
7 5
 import fs from '../fs.js'
8 6
 import getUUID from '../utils/uuid'
9 7
 

+ 42
- 0
src/polyfill/EventTarget.js View File

@@ -0,0 +1,42 @@
1
+// Copyright 2016 wkh237@github. All rights reserved.
2
+// Use of this source code is governed by a MIT-style license that can be
3
+// found in the LICENSE file.
4
+
5
+export default class EventTarget {
6
+
7
+  listeners : any;
8
+
9
+  constructor() {
10
+    this.listeners = {}
11
+  }
12
+
13
+  addEventListener(type:string, cb : () => void) {
14
+    if(!(type in this.listeners)) {
15
+      this.listeners[type] = []
16
+    }
17
+    this.listeners[type].push(cb)
18
+  }
19
+
20
+  removeEventListener(type:string, cb:() => any) {
21
+    if(!(type in this.listeners))
22
+      return
23
+    let handlers = this.listeners[type]
24
+    for(let i in handlers) {
25
+      if(cb === handlers[i]) {
26
+        handlers.splice(i,1)
27
+        return this.removeEventListener(type, cb)
28
+      }
29
+    }
30
+  }
31
+
32
+  dispatchEvent(event:Event) {
33
+    if(!(event.type in this.listeners))
34
+      return
35
+    let handlers = this.listeners[event.type]
36
+    for(let i in handlers) {
37
+      handlers[i].call(this, event)
38
+    }
39
+
40
+  }
41
+
42
+}

+ 4
- 6
src/polyfill/File.js View File

@@ -1,9 +1,7 @@
1
-/**
2
- * @author wkh237
3
- * @since 2016/07/18
4
- * @description
5
- * Web API File object polyfill.
6
- */
1
+// Copyright 2016 wkh237@github. All rights reserved.
2
+// Use of this source code is governed by a MIT-style license that can be
3
+// found in the LICENSE file.
4
+
7 5
 import fs from '../fs.js'
8 6
 import Blob from './Blob.js'
9 7
 

+ 167
- 7
src/polyfill/XMLHttpRequest.js View File

@@ -1,15 +1,175 @@
1
-export default class XMLHttpRequest {
1
+// Copyright 2016 wkh237@github. All rights reserved.
2
+// Use of this source code is governed by a MIT-style license that can be
3
+// found in the LICENSE file.
2 4
 
3
-  constructor(...args) {
4
-    console.log('XMLHttpRequest constructor called', args)
5
+import RNFetchBlob from '../index.js'
6
+import EventTarget from './EventTarget.js'
7
+
8
+export default class XMLHttpRequest extends EventTarget{
9
+
10
+  onreadystatechange : () => void;
11
+  onabort : () => void;
12
+  onerror : () => void;
13
+  onload : () => void;
14
+  onloadstart : () => void;
15
+  onprogress : () => void;
16
+  ontimeout : () => void;
17
+  onloadend : () => void;
18
+
19
+  readyState : number;
20
+  response : any;
21
+  responseText : any;
22
+  responseType : '' | 'arraybuffer' | 'blob' | 'document' | 'json' | 'text';
23
+  // TODO : not suppoted for now
24
+  responseURL : null;
25
+  responseXML : null;
26
+  status : number;
27
+  statusText : string;
28
+  timeout : number;
29
+
30
+  // RNFetchBlob compatible data structure
31
+  _config : RNFetchBlobConfig;
32
+  _url : any;
33
+  _method : string;
34
+  _headers: any;
35
+  _body: any;
36
+
37
+  // RNFetchBlob promise object, which has `progress`, `uploadProgress`, and
38
+  // `cancel` methods.
39
+  _task: any;
40
+
41
+  constructor() {
42
+    super()
43
+    console.log('---------------------------------')
44
+    console.log('XMLHttpRequest constructor called')
45
+    this._config = {}
46
+    this._args = {}
47
+    this._headers = {}
48
+    this.readyState = 0
49
+    this.response = null
50
+    this.responseText = null
51
+  }
52
+
53
+  // XMLHttpRequest.open, always async, user and password not supported.
54
+  open(method:string, url:string, async:true, user:any, password:any) {
55
+    console.log('---------------------------------')
56
+    console.log('XMLHttpRequest open called', method, url, async, user, password)
57
+    this._method = method
58
+    this._url = url
59
+    this.readyState = 1
60
+    if(this.onload)
61
+      this.onload()
62
+    if(this.onloadstart)
63
+      this.onloadstart()
5 64
   }
6 65
 
7
-  send(...data) {
8
-    console.log('XMLHttpRequest send called', data)
66
+  addEventListener(event, listener) {
67
+    console.log('---------------------------------')
68
+    console.log('XMLHttpRequest add listener', event, listener.toString())
69
+    this.addEventListener(event, listener)
70
+  }
71
+
72
+  /**
73
+   * Invoke this function to send HTTP request, and set body.
74
+   * @param  {any} body Body in RNfetchblob flavor
75
+   */
76
+  send(body) {
77
+    console.log('---------------------------------')
78
+    console.log('XMLHttpRequest send called', body)
79
+    let [_method, _url, _headers] = this
80
+    console.log('sending request with args', _method, _url, _headers, body)
81
+
82
+    this._task = RNFetchBlob.fetch(_method, _url, _headers, body)
83
+    this._task
84
+        .uploadProgress(this._progressEvent)
85
+        .onProgress(this._progressEvent)
86
+        .then(this._onDone)
87
+        .catch(this._onError)
88
+  }
89
+
90
+  overrideMimeType(mime:string) {
91
+    this.headers['content-type'] = mime
92
+  }
93
+
94
+  setRequestHeader(name, value) {
95
+    console.log('XMLHttpRequest set header', name, value)
96
+    this._headers[name] = value
97
+  }
98
+
99
+  abort() {
100
+    console.log('---------------------------------')
101
+    console.log('XMLHttpRequest abort called', this._task)
102
+    this._task.cancel((err) => {
103
+      let e = {
104
+        timeStamp : Date.now(),
105
+      }
106
+      if(this.onabort)
107
+        this.onabort()
108
+      if(!err) {
109
+        e.detail = err
110
+        e.type = 'error'
111
+        this.dispatchEvent('error', e)
112
+      }
113
+      else {
114
+        e.type = 'abort'
115
+        this.dispatchEvent('abort', e)
116
+      }
117
+    })
118
+  }
119
+
120
+  getResponseHeader(field:string):string | null{
121
+
122
+  }
123
+
124
+  getAllResponseHeaders():string | null {
125
+
126
+  }
127
+
128
+  set onreadystatechange(handler:() => void) {
129
+    this.onreadystatechange = handler
130
+  }
131
+
132
+  _progressEvent(send:number, total:number) {
133
+    let lengthComputable = false
134
+    if(total && total >= 0)
135
+        lengthComputable = true
136
+    else {
137
+      this.dispatchEvent('progress',
138
+        { loaded : send, total, lengthComputable })
139
+    }
140
+
141
+    if(this.onprogress)
142
+      this.onprogress({loaded : send, total, lengthComputable})
143
+  }
144
+
145
+  _onError(err) {
146
+    this.statusText = err
147
+
148
+    if(String(err).match('timeout') !== null) {
149
+      if(this.ontimeout)
150
+        this.ontimeout()
151
+    }
152
+    else if(this.onerror) {
153
+      this.onerror({
154
+        type : 'error',
155
+        detail : err
156
+      })
157
+    }
9 158
   }
10 159
 
11
-  abort(...args) {
12
-    console.log('XMLHttpRequest abort called', data)
160
+  _onDone(resp) {
161
+    this.statusText = '200 OK'
162
+    switch(resp.type) {
163
+      case 'base64' :
164
+      this.responseType = 'text'
165
+      this.responseText = resp.text()
166
+      this.response = this.responseText
167
+      break;
168
+      case 'path' :
169
+      this.responseType = 'blob'
170
+      this.response = resp.blob()
171
+      break;
172
+    }
13 173
   }
14 174
 
15 175
 }

+ 3
- 4
src/scripts/prelink.js View File

@@ -13,15 +13,14 @@ var package = JSON.parse(fs.readFileSync(PACKAGE_JSON));
13 13
 var APP_NAME = package.name;
14 14
 var APPLICATION_MAIN = process.cwd() + '/android/app/src/main/java/com/' + APP_NAME.toLocaleLowerCase() + '/MainApplication.java';
15 15
 
16
-if(!fs.existsSync(APPLICATION_MAIN)) {
17
-  throw 'RNFetchBlob could not found link Android automatically, MainApplication.java not found in path : ' + APPLICATION_MAIN
18
-}
19
-
20 16
 var VERSION = checkVersion();
21 17
 console.log('RNFetchBlob detected app version .. ' + VERSION);
22 18
 
23 19
 if(VERSION >= 0.29) {
24 20
   console.log('RNFetchBlob patching MainApplication.java .. ');
21
+  if(!fs.existsSync(APPLICATION_MAIN)) {
22
+    throw 'RNFetchBlob could not link Android automatically, MainApplication.java not found in path : ' + APPLICATION_MAIN
23
+  }
25 24
   var main = fs.readFileSync(APPLICATION_MAIN);
26 25
   if(String(main).match('new RNFetchBlobPackage()') !== null) {
27 26
     console.log('skipped');