Skip to content
This repository was archived by the owner on Mar 16, 2019. It is now read-only.

Commit 2a5f183

Browse files
committed
#1 Change progress API usage
1 parent d36b915 commit 2a5f183

File tree

3 files changed

+64
-13
lines changed

3 files changed

+64
-13
lines changed

src/README.md

Lines changed: 44 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# react-native-fetch-blob [![npm version](https://badge.fury.io/js/react-native-fetch-blob.svg)](https://badge.fury.io/js/react-native-fetch-blob)
22

3-
A react-native module for fetch file/image with custom headers, supports blob response data.
3+
A react-native module for fetch file/image with custom headers, supports blob response data, and upload/download progress.
44

55
If you're dealing with image or file server that requires an `Authorization` token in the header, or you're having problem with `fetch` API when receiving blob data, you might try this module (this is also the reason why I made this).
66

@@ -10,13 +10,23 @@ This module enables you upload/download binary data in js, see [Examples](#user-
1010

1111
The source code is very simple, just an implementation of native HTTP request, supports both Android (uses awesome native library [AsyncHttpClient](https://github.com/AsyncHttpClient/async-http-client])) and IOS.
1212

13+
## Major Changes
14+
15+
| Version | |
16+
|---|---|
17+
| 0.3 | Upload/Download octet-stream and form-data |
18+
| 0.4 | Add base-64 encode/decode library and API |
19+
| 0.4.1 | Fixe upload form-data missing file extension problem on Android |
20+
| 0.4.2 | Supports upload/download progress |
21+
1322
## Usage
1423

1524
* [Installation](#user-content-installation)
1625
* [Examples](#user-content-usage)
1726
* [Download file](#user-content-download-example--fetch-files-that-needs-authorization-token)
1827
* [Upload file](#user-content-upload-example--dropbox-files-upload-api)
1928
* [Multipart/form upload](#user-content-multipartform-data-example--post-form-data-with-file-and-data)
29+
* [Upload/Download progress](#user-content-uploaaddownload-progress)
2030
* [API](#user-content-api)
2131

2232
## Installation
@@ -114,9 +124,30 @@ Elements have property `filename` will be transformed into binary format, otherw
114124
})
115125
```
116126

127+
#### Upload/Download progress
128+
129+
In `version >= 0.4.2` it is possible to know the upload/download progress.
130+
131+
```js
132+
RNFetchBlob.fetch('POST', 'http://www.example.com/upload', {
133+
... some headers,
134+
'Content-Type' : 'octet-stream'
135+
}, base64DataString)
136+
.progress((received, total) => {
137+
console.log('progress', received / total)
138+
})
139+
.then((resp) => {
140+
// ...
141+
})
142+
.catch((err) => {
143+
// ...
144+
})
145+
```
146+
147+
117148
## API
118149

119-
#### `fetch(method, url, headers, body):Promise<FetchBlobResponse> `
150+
#### `fetch(method, url, headers, body):Promise<FetchBlobResponse>`
120151

121152
Send a HTTP request uses given headers and body, and return a Promise.
122153

@@ -128,9 +159,16 @@ HTTP request destination url.
128159
Headers of HTTP request, value of headers should be `stringified`, if you're uploading binary files, content-type should be `application/octet-stream` or `multipart/form-data`(see examples above).
129160
#### body:`string | Array<Object>` (Optional)
130161
Body of the HTTP request, body can either be a BASE64 string, or an array contains object elements, each element have 2 required property `name`, and `data`, and 1 optional property `filename`, once `filename` is set, content in `data` property will be consider as BASE64 string that will be converted into byte array later.
131-
132162
When body is a base64 string , this string will be converted into byte array in native code, and the request body will be sent as `application/octet-stream`.
133163

164+
### `fetch(...).progress(eventListener):Promise<FetchBlobResponse>` added in `0.4.2`
165+
166+
Register on progress event handler for a fetch request.
167+
168+
#### eventListener:`(sendOrReceivedBytes:number, totalBytes:number)`
169+
170+
A function that triggers when there's data received/sent, first argument is the number of sent/received bytes, and second argument is expected total bytes number.
171+
134172
#### `base64`
135173

136174
A helper object simply uses [base-64](https://github.com/mathiasbynens/base64) for decode and encode BASE64 data.
@@ -152,7 +190,8 @@ When `fetch` success, it resolve a `FetchBlobResponse` object as first argument.
152190
returns decoded base64 string (done in js context)
153191

154192

155-
### TODO
193+
### Upcoming Features
156194

157-
* Save file to storage
195+
* Save file to storage directly
196+
* Upload file from storage directly
158197
* Custom MIME type in form data

src/index.js

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/**
22
* @author wkh237
3-
* @version 0.3.3
3+
* @version 0.4.2
44
*/
55

66
import {
@@ -15,34 +15,43 @@ const emitter = (Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEvent
1515
const RNFetchBlob = NativeModules.RNFetchBlob
1616

1717
// Show warning if native module not detected
18-
if(RNFetchBlob === void 0) {
18+
if(!RNFetchBlob || !RNFetchBlob.fetchBlobForm || !RNFetchBlob.fetchBlob) {
1919
console.warn(
20-
'react-native-fetch-blob could not find native module.',
20+
'react-native-fetch-blob could not find valid native module.',
2121
'please make sure you have linked native modules using `rnpm link`,',
2222
'and restart RN packager or manually compile IOS/Android project.'
2323
)
2424
}
2525

26+
const config = function(options) {
27+
return { fetch : fetch.bind(options) }
28+
}
29+
2630
// Promise wrapper function
27-
const fetch = (...args) => {
31+
const fetch = function(...args) {
32+
33+
let options = this || {}
2834

2935
// create task ID for receiving progress event
3036
let taskId = getUUID()
37+
3138
let promise = new Promise((resolve, reject) => {
3239

3340
let [method, url, headers, body] = [...args]
3441
let nativeMethodName = Array.isArray(body) ? 'fetchBlobForm' : 'fetchBlob'
42+
43+
// on progress event listener
3544
let subscription = emitter.addListener('RNFetchBlobProgress', (e) => {
3645
if(e.taskId === taskId && promise.onProgress) {
3746
promise.onProgress(e.written, e.total)
3847
}
3948
})
4049

41-
RNFetchBlob[nativeMethodName](taskId, method, url, headers || {}, body, (err, ...data) => {
50+
let req = RNFetchBlob[nativeMethodName]
51+
req(taskId, method, url, headers || {}, body, (err, ...data) => {
4252

4353
// task done, remove event listener
4454
subscription.remove()
45-
4655
if(err)
4756
reject(new Error(err, ...data))
4857
else
@@ -52,7 +61,10 @@ const fetch = (...args) => {
5261

5362
})
5463

55-
promise.onProgress = null
64+
promise.progress = (fn) => {
65+
promise.onProgress = fn
66+
return promise
67+
}
5668

5769
return promise
5870

src/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "react-native-fetch-blob",
3-
"version": "0.4.1",
3+
"version": "0.4.2",
44
"description": "A react-native plugin for fetch blob data via HTTP.",
55
"main": "index.js",
66
"scripts": {

0 commit comments

Comments
 (0)