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

Fetch API

wkh237 edited this page Aug 5, 2016 · 56 revisions

Diagram

config(options:RNFetchBlobConfig):fetch

0.5.0

Config API was introduced in v0.5.0 which provides some options for the fetch task.

see RNFetchBlobConfig

fetch(method, url, headers, body):Promise<RNFetchBlobResponse>

legacy

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

method:string Required

HTTP request method, can be one of get, post, delete, and put, case-insensitive.

url:string Required

HTTP request destination url.

headers:object (Optional)

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).

body:string | Array<Object> (Optional)

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, data, and optional property filename, once filename is set, content in data property will be considered as a path of a file, or a BASE64 string which will be converted into byte array later.

For example

// Post binary data using base64 encoding
RNFetchBlob.fetch('POST', 'http://myupload.com/upload', { 
        'Content-Type' : 'application/octet-stream' 
    }, RNFetchBlob.base64.encode(mydata))

// Post binary data from existing file
RNFetchBlob.fetch('POST', 'http://myupload.com/upload', { 
        'Content-Type' : 'application/octet-stream' 
    }, RNFetchBlob.wrap(path_to_the_file))

// Post form data 
RNFetchBlob.fetch('POST', 'http://myupload.com/upload', { 
        'Content-Type' : 'multipart/form-data' 
    }, [
        name : 'user_name', data : 'Bill',
        // binary field data from a file path, use `wrap` method to wrap the path
        name : 'avatar', filename : 'avatar.jpg', data : RNFetchBlob.wrap(path_to_the_file),
        // binary field data encoded in BASE64
        name : 'pet-avatar', filename : 'pet-avatar.jpg', data : RNFetchBlob.base64.encode(image_data),
    ])

fetch(...).progress(eventListener):Promise<RNFetchBlobResponse>

0.6.1

Register on progress event handler for a fetch request.

eventListener:(sendOrReceivedBytes:number, totalBytes:number)

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.

RNFetchBlob.fetch('GET', 'http://mydownload.com/image/1')
    .progress((received, total) => {
        console.log('progress ' + Math.floor(received/total*100) + '%')
    })

fetch(...).uploadProgress(eventListener):Promise<RNFetchBlobResponse>

Just like progress but the listener invoked when data write to HTTP request stream. uploadProgress is not supported on Android before version 0.7.0.

RNFetchBlob.fetch('GET', 'http://mydownload.com/image/1')
    .uploadProgress((received, total) => {
        console.log('progress ' + Math.floor(received/total*100) + '%')
    })

The progress event triggers at a very high frequency, it is recommended to add a debounce mechanism when an UI update is triggered by progress event. For example

RNFetchBlob.fetch('GET', 'http://largefile.com/file/1')
    .progress((received, total) => {
        if(Date.now() - this.state.lastTick < 1000)
            return
        this.setState({ 
            progress : received/total,
            lastTick : Date.now()
        })
    })

fetch(...).cancel(eventListener):Promise<RNFetchBlobResponse>

0.7.0

Cancel a HTTP request which will cause the fetch call throw an rejected promise. Argument eventListener is optional.

let task = RNFetchbBlob.fetch('GET', 'http://example.com/file/1')

task.then((data) => {
  // .. success
})
.catch((err) => {
  console.log(err)
})

// cancel the HTTP request
task.cancel((err, taskId) => {
  // task successfully canceled
})

wrap(path:string):string

Simply prepend RNFetchBlob-file:// to a path, this make the file path becomes recognizable to native fetch method.

session(name:string):RNFetchBlobSession

Session API helps managing cached files, the following code, will try to return an existing session object with the given name, if it does not exist, create one.

RNFetchBlob.session('mysession')

see Sessions API for more usages.

base64

0.4.2

A helper class simply uses base-64 for decode and encode BASE64 data.

RNFetchBlob.base64.encode(data)
RNFetchBlob.base64.decode(data)

Work In Progress

Document of work in progress functionalities, these functions will be launched in next release

RNFB as Fetch

0.8.2

If you have existing APIs that uses whatwg-fetch you can uses our fetch replacement so that you don't have to change the existing code. The differences between Official fetch and ours is that official fetch uses whatwg-fetch js library which wraps XMLHttpRequest polyfill under the hood, and our implementation wraps RNFetchBlob module.

import RNFetchBlob from 'react-native-fetch-blob'

const Fetch = RNFetchBlob.polyfill.Fetch
// replace built-in fetch
window.fetch = new Fetch({
    // enable this option so that the fetch function automatically convert response data
    auto : true,
    // Whenever a response data received, the module will match the Content-Type with strings in this array.
    // If it contains any one of substring in this array, the response body will be considered as binary data.
    // By default, it only converts response data with content type contains string `application/octet`.
    binaryContentTypes : [
        'image/',
        'video/',
        'audio/',
        'foo/',
    ]
})

// use as usual

fetch('http://www.example.com/the/resource', {
    method : 'GET',
    headers : { /* whatever it goes */ },
})
.then((res) => {
    if(res.ok)
        return res.text()
    else
        throw 'fetch failed, status code: '+ res.status
})
.catch((err) => {
   // ...
})
Clone this wiki locally