Gathering detailed insights and metrics for rn-fetch-blob
Gathering detailed insights and metrics for rn-fetch-blob
Gathering detailed insights and metrics for rn-fetch-blob
Gathering detailed insights and metrics for rn-fetch-blob
@types/rn-fetch-blob
TypeScript definitions for rn-fetch-blob
react-native-image-offline
React Native library for iOS and Android offline image storage. This library provides most of the capabilities for an application to display pre-loaded images when offline. (This library has a dependency on **rn-fetch-blob**. Refer [here](https://github.c
react-native-blob-util
A module provides upload, download, and files access API. Supports file stream read/write for process large files.
fetch-blob
Blob & File implementation in Node.js, originally from node-fetch.
A project committed to making file access and data transfer easier, efficient for React Native developers.
npm install rn-fetch-blob
v0.13.0-beta-1
Published on 04 Apr 2022
v0.12.0
Published on 19 Dec 2019
Revert to fix regressions
Published on 27 Sept 2019
podspec file fix
Published on 26 Sept 2019
Bug fixes and a few new features
Published on 26 Sept 2019
React Native 60 Support
Published on 14 Jul 2019
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
2,846 Stars
1,467 Commits
788 Forks
21 Watching
137 Branches
2 Contributors
Updated on 26 Nov 2024
JavaScript (39.77%)
Java (33.86%)
Objective-C (26.25%)
Ruby (0.12%)
Cumulative downloads
Total Downloads
Last day
-4.8%
20,480
Compared to previous day
Last week
4.2%
107,565
Compared to previous week
Last month
1.5%
446,694
Compared to previous month
Last year
5.4%
5,433,761
Compared to previous year
A project committed to making file access and data transfer easier and more efficient for React Native developers.
rn-fetch-blob version 0.10.16 is only compatible with react native 0.60 and up. It should have been a major version bump, we apologize for the mistake. If you are not yet upgraded to react native 0.60 or above, you should remain on rn-fetch-blob version 0.10.15
This project was started in the cause of solving issue facebook/react-native#854, React Native's lacks of Blob
implementation which results into problems when transferring binary data.
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.
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
Install package from npm
1npm install --save rn-fetch-blob
Or if using CocoaPods, add the pod to your Podfile
pod 'rn-fetch-blob',
:path => '../node_modules/rn-fetch-blob'
After 0.10.3
you can install this package directly from Github
1# replace <branch_name> with any one of the branches 2npm install --save github:joltup/rn-fetch-blob#<branch_name>
Manually Link Native Modules
If automatically linking doesn't work for you, see instructions on manually linking.
Automatically Link Native Modules
For projects 0.29.2 < 0.69.0 , simply link native packages via the following command (note: rnpm has been merged into react-native)
react-native link rn-fetch-blob
This link command no longer works for react-native 0.69.0+
As for projects < 0.29 you need rnpm
to link native packages
1rnpm link
You also might need add the following lines to AndroidManifest.xml
1<manifest xmlns:android="http://schemas.android.com/apk/res/android" 2 package="com.rnfetchblobtest" 3 android:versionCode="1" 4 android:versionName="1.0"> 5 6 <uses-permission android:name="android.permission.INTERNET" /> 7+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 8 ... 9 <intent-filter> 10 <category android:name="android.intent.category.LAUNCHER" /> 11+ <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/> 12 ...
For projects < 0.28
React Native has changed OkHttp version in 0.27, if your project is older than 0.28 you have to explicitly specify OkHttp version in node_modules/rn-fetch-blob/android/build.gradle
1dependencies { 2 implementation 'com.facebook.react:react-native:+' 3+ implementation 'com.squareup.okhttp3:okhttp:3.4.1' 4- //{RNFetchBlob_PRE_0.28_DEPDENDENCY} 5}
The link script might not take effect if you have non-default project structure, please visit the wiki to link the package manually.
Grant Permission to External storage for Android 5.0 or lower
The mechanism for granting Android permissions has slightly different since Android 6.0 released, please refer to Official Document.
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
.
1<manifest xmlns:android="http://schemas.android.com/apk/res/android" 2 package="com.rnfetchblobtest" 3 android:versionCode="1" 4 android:versionName="1.0"> 5 6 <uses-permission android:name="android.permission.INTERNET" /> 7 <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/> 8+ <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 9+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 10+ <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" /> 11 ... 12
Also, if you're going to use Android Download Manager
you have to add this to AndroidManifest.xml
1 <intent-filter> 2 <action android:name="android.intent.action.MAIN" /> 3 <category android:name="android.intent.category.LAUNCHER" /> 4+ <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/> 5 </intent-filter>
If you are going to use the wifiOnly
flag, you need to add this to AndroidManifest.xml
1+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 2 ... 3
Grant Access Permission for Android 6.0
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.
ES6
The module uses ES6 style export statement, simply use import
to load the module.
1import RNFetchBlob from "rn-fetch-blob";
ES5
If you're using ES5 require statement to load the module, please add default
. See here for more detail.
var RNFetchBlob = require('rn-fetch-blob').default
After 0.8.0
rn-fetch-blob 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
To sum up:
Content-Type
header does not matter. When the body is an Array
we will set proper content type for you.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.RNFetchBlob-file://
(which can simply be done by RNFetchBlob.wrap(PATH_TO_THE_FILE)
), it will try to find the data from the URI string after RNFetchBlob-file://
and use it as the request body.Content-Type
header not containing ;BASE64
or application/octet
.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'
After 0.9.4, we disabled
Chunked
transfer encoding by default, if you're going to use it, you should explicitly set headerTransfer-Encoding
toChunked
.
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.
1// send http request in a new thread (using native code) 2RNFetchBlob.fetch("GET", "http://www.example.com/images/img1.png", { 3 Authorization: "Bearer access-token...", 4 // more headers .. 5}) 6 .then((res) => { 7 let status = res.info().status; 8 9 if (status == 200) { 10 // the conversion is done in native code 11 let base64Str = res.base64(); 12 // the following conversions are done in js, it's SYNC 13 let text = res.text(); 14 let json = res.json(); 15 } else { 16 // handle other status codes 17 } 18 }) 19 // Something went wrong: 20 .catch((errorMessage, statusCode) => { 21 // error handling 22 });
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.
These files won't be removed automatically, please refer to Cache File Management
1RNFetchBlob.config({ 2 // add this option that makes response data to be stored as a file, 3 // this is much more performant. 4 fileCache: true, 5}) 6 .fetch("GET", "http://www.example.com/file/example.zip", { 7 //some headers .. 8 }) 9 .then((res) => { 10 // the temp file path 11 console.log("The file saved to ", res.path()); 12 });
Set Temp File Extension
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
.
1RNFetchBlob.config({ 2 fileCache: true, 3 // by adding this option, the temp files will have a file extension 4 appendExt: "png", 5}) 6 .fetch("GET", "http://www.example.com/file/example.zip", { 7 //some headers .. 8 }) 9 .then((res) => { 10 // the temp file path with file extension `png` 11 console.log("The file saved to ", res.path()); 12 // Beware that when using a file path as Image source on Android, 13 // you must prepend "file://"" before the file path 14 imageView = ( 15 <Image 16 source={{ 17 uri: 18 Platform.OS === "android" 19 ? "file://" + res.path() 20 : "" + res.path(), 21 }} 22 /> 23 ); 24 });
Use Specific File Path
If you prefer a particular file path rather than randomly generated one, you can use path
option. We've added several constants in v0.5.0 which represents commonly used directories.
1let dirs = RNFetchBlob.fs.dirs; 2RNFetchBlob.config({ 3 // response data will be saved to this path if it has access right. 4 path: dirs.DocumentDir + "/path-to-file.anything", 5}) 6 .fetch("GET", "http://www.example.com/file/example.zip", { 7 //some headers .. 8 }) 9 .then((res) => { 10 // the path should be dirs.DocumentDir + 'path-to-file.anything' 11 console.log("The file saved to ", res.path()); 12 });
These files won't be removed automatically, please refer to Cache File Management
rn-fetch-blob
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.
1RNFetchBlob.fetch( 2 "POST", 3 "https://content.dropboxapi.com/2/files/upload", 4 { 5 Authorization: "Bearer access-token...", 6 "Dropbox-API-Arg": JSON.stringify({ 7 path: "/img-from-react-native.png", 8 mode: "add", 9 autorename: true, 10 mute: false, 11 }), 12 "Content-Type": "application/octet-stream", 13 // here's the body you're going to send, should be a BASE64 encoded string 14 // (you can use "base64"(refer to the library 'mathiasbynens/base64') APIs to make one). 15 // The data will be converted to "byte array"(say, blob) before request sent. 16 }, 17 base64ImageString 18) 19 .then((res) => { 20 console.log(res.text()); 21 }) 22 .catch((err) => { 23 // error handling .. 24 });
If you're going to use a file
as request body, just wrap the path with wrap
API.
1RNFetchBlob.fetch( 2 "POST", 3 "https://content.dropboxapi.com/2/files/upload", 4 { 5 // dropbox upload headers 6 Authorization: "Bearer access-token...", 7 "Dropbox-API-Arg": JSON.stringify({ 8 path: "/img-from-react-native.png", 9 mode: "add", 10 autorename: true, 11 mute: false, 12 }), 13 "Content-Type": "application/octet-stream", 14 // Change BASE64 encoded data to a file path with prefix `RNFetchBlob-file://`. 15 // Or simply wrap the file path with RNFetchBlob.wrap(). 16 }, 17 RNFetchBlob.wrap(PATH_TO_THE_FILE) 18) 19 .then((res) => { 20 console.log(res.text()); 21 }) 22 .catch((err) => { 23 // error handling .. 24 });
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).
Elements have property filename
will be transformed into binary format, otherwise, it turns into utf8 string.
1RNFetchBlob.fetch( 2 "POST", 3 "http://www.example.com/upload-form", 4 { 5 Authorization: "Bearer access-token", 6 otherHeader: "foo", 7 "Content-Type": "multipart/form-data", 8 }, 9 [ 10 // element with property `filename` will be transformed into `file` in form data 11 { name: "avatar", filename: "avatar.png", data: binaryDataInBase64 }, 12 // custom content type 13 { 14 name: "avatar-png", 15 filename: "avatar-png.png", 16 type: "image/png", 17 data: binaryDataInBase64, 18 }, 19 // part file from storage 20 { 21 name: "avatar-foo", 22 filename: "avatar-foo.png", 23 type: "image/foo", 24 data: RNFetchBlob.wrap(path_to_a_file), 25 }, 26 // elements without property `filename` will be sent as plain text 27 { name: "name", data: "user" }, 28 { 29 name: "info", 30 data: JSON.stringify({ 31 mail: "example@example.com", 32 tel: "12345678", 33 }), 34 }, 35 ] 36) 37 .then((resp) => { 38 // ... 39 }) 40 .catch((err) => { 41 // ... 42 });
What if you want to append a file to form data? Just like 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).
1 2 RNFetchBlob.fetch('POST', 'http://www.example.com/upload-form', { 3 Authorization : "Bearer access-token", 4 otherHeader : "foo", 5 // this is required, otherwise it won't be process as a multipart/form-data request 6 'Content-Type' : 'multipart/form-data', 7 }, [ 8 // append field data from file path 9 { 10 name : 'avatar', 11 filename : 'avatar.png', 12 // Change BASE64 encoded data to a file path with prefix `RNFetchBlob-file://`. 13 // Or simply wrap the file path with RNFetchBlob.wrap(). 14 data: RNFetchBlob.wrap(PATH_TO_THE_FILE) 15 }, 16 { 17 name : 'ringtone', 18 filename : 'ring.mp3', 19 // use custom MIME type 20 type : 'application/mp3', 21 // upload a file from asset is also possible in version >= 0.6.2 22 data : RNFetchBlob.wrap(RNFetchBlob.fs.asset('default-ringtone.mp3')) 23 } 24 // elements without property `filename` will be sent as plain text 25 { name : 'name', data : 'user'}, 26 { name : 'info', data : JSON.stringify({ 27 mail : 'example@example.com', 28 tel : '12345678' 29 })}, 30 ]).then((resp) => { 31 // ... 32 }).catch((err) => { 33 // ... 34 })
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.
1RNFetchBlob.fetch( 2 "POST", 3 "http://www.example.com/upload", 4 { 5 //... some headers, 6 "Content-Type": "octet-stream", 7 }, 8 base64DataString 9) 10 // listen to upload progress event 11 .uploadProgress((written, total) => { 12 console.log("uploaded", written / total); 13 }) 14 // listen to download progress event 15 .progress((received, total) => { 16 console.log("progress", received / total); 17 }) 18 .then((resp) => { 19 // ... 20 }) 21 .catch((err) => { 22 // ... 23 });
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.
1RNFetchBlob.fetch( 2 "POST", 3 "http://www.example.com/upload", 4 { 5 //... some headers, 6 "Content-Type": "octet-stream", 7 }, 8 base64DataString 9) 10 // listen to upload progress event, emit every 250ms 11 .uploadProgress({ interval: 250 }, (written, total) => { 12 console.log("uploaded", written / total); 13 }) 14 // listen to download progress event, every 10% 15 .progress({ count: 10 }, (received, total) => { 16 console.log("progress", received / total); 17 }) 18 .then((resp) => { 19 // ... 20 }) 21 .catch((err) => { 22 // ... 23 });
After 0.7.0
it is possible to cancel an HTTP request. Upon cancellation, it throws a promise rejection, be sure to catch it.
1let task = RNFetchBlob.fetch('GET', 'http://example.com/file/1') 2 3task.then(() => { ... }) 4 // handle request cancelled rejection 5 .catch((err) => { 6 console.log(err) 7 }) 8// cancel the request, the callback function is optional 9task.cancel((err) => { ... }) 10
0.9.0
If you have existing code that uses whatwg-fetch
(the official fetch), it's not necessary to replace them with RNFetchblob.fetch
, you can simply use our Fetch Replacement. The difference between Official them is official fetch uses whatwg-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.
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
.
Media Scanner
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.
1RNFetchBlob.config({ 2 // DCIMDir is in external storage 3 path: dirs.DCIMDir + "/music.mp3", 4}) 5 .fetch("GET", "http://example.com/music.mp3") 6 .then((res) => 7 RNFetchBlob.fs.scanFile([{ path: res.path(), mime: "audio/mpeg" }]) 8 ) 9 .then(() => { 10 // scan file success 11 }) 12 .catch((err) => { 13 // scan file error 14 });
Download Manager
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.
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.
When download complete, DownloadManager will generate a file path so that you can deal with it.
1RNFetchBlob.config({ 2 addAndroidDownloads: { 3 useDownloadManager: true, // <-- this is the only thing required 4 // Optional, override notification setting (default to true) 5 notification: false, 6 // Optional, but recommended since android DownloadManager will fail when 7 // the url does not contains a file extension, by default the mime type will be text/plain 8 mime: "text/plain", 9 description: "File downloaded by download manager.", 10 }, 11}) 12 .fetch("GET", "http://example.com/file/somefile") 13 .then((resp) => { 14 // the path of downloaded file 15 resp.path(); 16 });
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.
Download Notification and Visibility in Download App (Android Only)
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
.
1RNFetchBlob.config({ 2 fileCache : true, 3 // android only options, these options be a no-op on IOS 4 addAndroidDownloads : { 5 // Show notification when response data transmitted 6 notification : true, 7 // Title of download notification 8 title : 'Great ! Download Success ! :O ', 9 // File description (not notification description) 10 description : 'An image file.', 11 mime : 'image/png', 12 // Make the file scannable by media scanner 13 mediaScannable : true, 14 } 15}) 16.fetch('GET', 'http://example.com/image1.png') 17.then(...)
Open Downloaded File with Intent
This is a new feature added in 0.9.0
if you're going to open a file path using official Linking 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.
Download and install an APK programmatically
1const android = RNFetchBlob.android; 2 3RNFetchBlob.config({ 4 addAndroidDownloads: { 5 useDownloadManager: true, 6 title: "awesome.apk", 7 description: "An APK that will be installed", 8 mime: "application/vnd.android.package-archive", 9 mediaScannable: true, 10 notification: true, 11 }, 12}) 13 .fetch("GET", `http://www.example.com/awesome.apk`) 14 .then((res) => { 15 android.actionViewIntent( 16 res.path(), 17 "application/vnd.android.package-archive" 18 ); 19 });
Or show an image in image viewer
1android.actionViewIntent(PATH_OF_IMG, "image/png");
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.
Before start using file APIs, we recommend read Differences between File Source first.
File Access APIs
See File API for more information
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.
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)
The file stream event has a default throttle(10ms) and buffer size which preventing it cause too much overhead to main thread, yo can also tweak these values.
1let data = ''
2RNFetchBlob.fs.readStream(
3 // file path
4 PATH_TO_THE_FILE,
5 // encoding, should be one of `base64`, `utf8`, `ascii`
6 'base64',
7 // (optional) buffer size, default to 4096 (4095 for BASE64 encoded data)
8 // when reading file in BASE64 encoding, buffer size must be multiples of 3.
9 4095)
10.then((ifstream) => {
11 ifstream.open()
12 ifstream.onData((chunk) => {
13 // when encoding is `ascii`, chunk will be an array contains numbers
14 // otherwise it will be a string
15 data += chunk
16 })
17 ifstream.onError((err) => {
18 console.log('oops', err)
19 })
20 ifstream.onEnd(() => {
21 <Image source={{ uri : 'data:image/png,base64' + data }}
22 })
23})
When using writeStream
, the stream object becomes writable, and you can then perform operations like write
and close
.
Since version 0.10.9 write()
resolves with the RNFetchBlob
instance so you can promise-chain write calls:
1RNFetchBlob.fs 2 .writeStream( 3 PATH_TO_FILE, 4 // encoding, should be one of `base64`, `utf8`, `ascii` 5 "utf8", 6 // should data append to existing content ? 7 true 8 ) 9 .then((ofstream) => ofstream.write("foo")) 10 .then((ofstream) => ofstream.write("bar")) 11 .then((ofstream) => ofstream.write("foobar")) 12 .then((ofstream) => ofstream.close()) 13 .catch(console.error);
or
1RNFetchBlob.fs
2 .writeStream(
3 PATH_TO_FILE,
4 // encoding, should be one of `base64`, `utf8`, `ascii`
5 "utf8",
6 // should data append to existing content ?
7 true
8 )
9 .then((stream) =>
10 Promise.all([
11 stream.write("foo"),
12 stream.write("bar"),
13 stream.write("foobar"),
14 ])
15 )
16 // Use array destructuring to get the stream object from the first item of the array we get from Promise.all()
17 .then(([stream]) => stream.close())
18 .catch(console.error);
You should NOT do something like this:
1RNFetchBlob.fs
2 .writeStream(
3 PATH_TO_FILE,
4 // encoding, should be one of `base64`, `utf8`, `ascii`
5 "utf8",
6 // should data append to existing content ?
7 true
8 )
9 .then((ofstream) => {
10 // BAD IDEA - Don't do this, those writes are unchecked:
11 ofstream.write("foo");
12 ofstream.write("bar");
13 ofstream.close();
14 })
15 .catch(console.error); // Cannot catch any write() errors!
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.
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
1// remove file using RNFetchblobResponse.flush() object method 2RNFetchblob.config({ 3 fileCache: true, 4}) 5 .fetch("GET", "http://example.com/download/file") 6 .then((res) => { 7 // remove cached file from storage 8 res.flush(); 9 }); 10 11// remove file by specifying a path 12RNFetchBlob.fs.unlink("some-file-path").then(() => { 13 // ... 14});
You can also group requests by using session
API and use dispose
to remove them all when needed.
1 2 RNFetchblob.config({ 3 fileCache : true 4 }) 5 .fetch('GET', 'http://example.com/download/file') 6 .then((res) => { 7 // set session of a response 8 res.session('foo') 9 }) 10 11 RNFetchblob.config({ 12 // you can also set session beforehand 13 session : 'foo' 14 fileCache : true 15 }) 16 .fetch('GET', 'http://example.com/download/file') 17 .then((res) => { 18 // ... 19 }) 20 21 // or put an existing file path to the session 22 RNFetchBlob.session('foo').add('some-file-path') 23 // remove a file path from the session 24 RNFetchBlob.session('foo').remove('some-file-path') 25 // list paths of a session 26 RNFetchBlob.session('foo').list() 27 // remove all files in a session 28 RNFetchBlob.session('foo').dispose().then(() => { ... }) 29
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
.
1RNFetchBlob.fetch( 2 "POST", 3 "http://example.com/upload", 4 { "Transfer-Encoding": "Chunked" }, 5 bodyData 6);
By default, rn-fetch-blob 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
1RNFetchBlob.config({ 2 trusty: true, 3}) 4 .fetch("GET", "https://mysite.com") 5 .then((resp) => { 6 // ... 7 });
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.
1RNFetchBlob.config({ 2 wifiOnly: true, 3}) 4 .fetch("GET", "https://mysite.com") 5 .then((resp) => { 6 // ... 7 });
After 0.8.0
we've made some Web API polyfills that makes some browser-based library available in RN.
Here's a sample app that uses polyfills to upload files to FireBase.
Read Stream and Progress Event Overhead
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.
Reduce RCT Bridge and BASE64 Overhead
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.
ASCII Encoding has /terrible Performance
Due to the lack of typed array implementation in JavascriptCore, and limitation of React Native structure, 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.
Concat and Replacing Files
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.
Blob
, from an existing file, the file WILL BE REMOVED if you close
the blob.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).0.9.6+
, use additional arguments to limit its frequency.file://
prefix.when you got a problem, have a look at Trouble Shooting or issues labeled Trouble Shooting, there'd be some helpful information.
See release notes
If you're interested in hacking this module, check our development guide, there might be some helpful information. Please feel free to make a PR or file an issue.
No vulnerabilities found.
Reason
license file detected
Details
Reason
0 existing vulnerabilities detected
Reason
binaries present in source code
Details
Reason
Found 12/19 approved changesets -- score normalized to 6
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More