From fead8a21b1e3d488f9574cb62d3c03ca973978bb Mon Sep 17 00:00:00 2001 From: David Wisner Date: Tue, 28 Jun 2022 09:58:46 +0800 Subject: [PATCH] remove config for 0.69.0, update readme --- .gitignore | 1 + README.md | 598 +++++++++++++++++++++++------------------ react-native.config.js | 7 - scripts/prelink.js | 71 ----- 4 files changed, 336 insertions(+), 341 deletions(-) delete mode 100644 react-native.config.js delete mode 100644 scripts/prelink.js diff --git a/.gitignore b/.gitignore index 418c56e5c..1e25f4d3d 100644 --- a/.gitignore +++ b/.gitignore @@ -38,6 +38,7 @@ local.properties # node_modules/ npm-debug.log +yarn.lock # BUCK buck-out/ diff --git a/README.md b/README.md index b5ca84c45..584845ccd 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # rn-fetch-blob + [![release](https://img.shields.io/github/release/joltup/rn-fetch-blob.svg?style=flat-square)](https://github.com/joltup/rn-fetch-blob/releases) [![npm](https://img.shields.io/npm/v/rn-fetch-blob.svg?style=flat-square)](https://www.npmjs.com/package/rn-fetch-blob) ![](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/joltup/rn-fetch-blob/wiki) [![npm](https://img.shields.io/npm/l/rn-fetch-blob.svg?maxAge=2592000&style=flat-square)]() A project committed to making file access and data transfer easier and more efficient for React Native developers. @@ -8,6 +9,7 @@ A project committed to making file access and data transfer easier and more effi 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 ## Features + - Transfer data directly from/to storage without BASE64 bridging - File API supports regular files, Asset files, and CameraRoll files - Native-to-native file manipulation API, reduce JS bridging performance loss @@ -16,28 +18,29 @@ rn-fetch-blob version 0.10.16 is only compatible with react native 0.60 and up. - JSON stream supported base on [Oboe.js](https://github.com/jimhigson/oboe.js/) @jimhigson ## TOC (visit [Wiki](https://github.com/joltup/rn-fetch-blob/wiki) to get the complete documentation) -* [About](#user-content-about) -* [Installation](#user-content-installation) -* [HTTP Data Transfer](#user-content-http-data-transfer) - * [Regular Request](#user-content-regular-request) - * [Download file](#download-example-fetch-files-that-need-authorization-token) - * [Upload file](#user-content-upload-example--dropbox-files-upload-api) - * [Multipart/form upload](#user-content-multipartform-data-example--post-form-data-with-file-and-data) - * [Upload/Download progress](#user-content-uploaddownload-progress) - * [Cancel HTTP request](#user-content-cancel-request) - * [Android Media Scanner, and Download Manager Support](#user-content-android-media-scanner-and-download-manager-support) - * [Self-Signed SSL Server](#user-content-self-signed-ssl-server) - * [Transfer Encoding](#user-content-transfer-encoding) - * [Drop-in Fetch Replacement](#user-content-drop-in-fetch-replacement) -* [File System](#user-content-file-system) - * [File access](#user-content-file-access) - * [File stream](#user-content-file-stream) - * [Manage cached files](#user-content-cache-file-management) -* [Web API Polyfills](#user-content-web-api-polyfills) -* [Performance Tips](#user-content-performance-tips) -* [API References](https://github.com/joltup/rn-fetch-blob/wiki/Fetch-API) -* [Caveats](#user-content-caveats) -* [Development](#user-content-development) + +- [About](#user-content-about) +- [Installation](#user-content-installation) +- [HTTP Data Transfer](#user-content-http-data-transfer) +- [Regular Request](#user-content-regular-request) +- [Download file](#download-example-fetch-files-that-need-authorization-token) +- [Upload file](#user-content-upload-example--dropbox-files-upload-api) +- [Multipart/form upload](#user-content-multipartform-data-example--post-form-data-with-file-and-data) +- [Upload/Download progress](#user-content-uploaddownload-progress) +- [Cancel HTTP request](#user-content-cancel-request) +- [Android Media Scanner, and Download Manager Support](#user-content-android-media-scanner-and-download-manager-support) +- [Self-Signed SSL Server](#user-content-self-signed-ssl-server) +- [Transfer Encoding](#user-content-transfer-encoding) +- [Drop-in Fetch Replacement](#user-content-drop-in-fetch-replacement) +- [File System](#user-content-file-system) +- [File access](#user-content-file-access) +- [File stream](#user-content-file-stream) +- [Manage cached files](#user-content-cache-file-management) +- [Web API Polyfills](#user-content-web-api-polyfills) +- [Performance Tips](#user-content-performance-tips) +- [API References](https://github.com/joltup/rn-fetch-blob/wiki/Fetch-API) +- [Caveats](#user-content-caveats) +- [Development](#user-content-development) ## About @@ -47,7 +50,6 @@ It is committed to making file access and transfer easier and more efficient for 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) - ## Installation Install package from npm @@ -76,28 +78,47 @@ If automatically linking doesn't work for you, see instructions on [manually lin **Automatically Link Native Modules** -For 0.29.2+ projects, simply link native packages via the following command (note: rnpm has been merged into react-native) +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 ```sh rnpm link ``` -Optionally, use the following command to add Android permissions to `AndroidManifest.xml` automatically +You also might need add the following lines to `AndroidManifest.xml` -```sh -RNFB_ANDROID_PERMISSIONS=true react-native link rn-fetch-blob +```diff + + + ++ + ... + + ++ + ... ``` -pre 0.29 projects +For projects < 0.28 -```sh -RNFB_ANDROID_PERMISSIONS=true rnpm link +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` + +```diff +dependencies { + implementation 'com.facebook.react:react-native:+' ++ implementation 'com.squareup.okhttp3:okhttp:3.4.1' +- //{RNFetchBlob_PRE_0.28_DEPDENDENCY} +} ``` The link script might not take effect if you have non-default project structure, please visit [the wiki](https://github.com/joltup/rn-fetch-blob/wiki/Manually-Link-Package) to link the package manually. @@ -152,7 +173,7 @@ ES6 The module uses ES6 style export statement, simply use `import` to load the module. ```js -import RNFetchBlob from 'rn-fetch-blob' +import RNFetchBlob from "rn-fetch-blob"; ``` ES5 @@ -165,7 +186,6 @@ var RNFetchBlob = require('rn-fetch-blob').default ## HTTP Data Transfer - ### Regular Request 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 @@ -176,8 +196,8 @@ To sum up: - 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. - To send binary data, you have two choices, use BASE64 encoded string or path points to a file contains the body. - - 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. - - Otherwise, if a string starts with `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. +- 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. +- Otherwise, if a string starts with `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. - To send the body as-is, simply use a `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'` @@ -189,21 +209,20 @@ To sum up: 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. ```js - // send http request in a new thread (using native code) -RNFetchBlob.fetch('GET', 'http://www.example.com/images/img1.png', { - Authorization : 'Bearer access-token...', - // more headers .. - }) +RNFetchBlob.fetch("GET", "http://www.example.com/images/img1.png", { + Authorization: "Bearer access-token...", + // more headers .. +}) .then((res) => { let status = res.info().status; - if(status == 200) { + if (status == 200) { // the conversion is done in native code - let base64Str = res.base64() + let base64Str = res.base64(); // the following conversions are done in js, it's SYNC - let text = res.text() - let json = res.json() + let text = res.text(); + let json = res.json(); } else { // handle other status codes } @@ -211,7 +230,7 @@ RNFetchBlob.fetch('GET', 'http://www.example.com/images/img1.png', { // Something went wrong: .catch((errorMessage, statusCode) => { // error handling - }) + }); ``` ### Download to storage directly @@ -221,19 +240,18 @@ If the response data is large, that would be a bad idea to convert it into BASE6 **These files won't be removed automatically, please refer to [Cache File Management](#user-content-cache-file-management)** ```js -RNFetchBlob - .config({ - // add this option that makes response data to be stored as a file, - // this is much more performant. - fileCache : true, - }) - .fetch('GET', 'http://www.example.com/file/example.zip', { +RNFetchBlob.config({ + // add this option that makes response data to be stored as a file, + // this is much more performant. + fileCache: true, +}) + .fetch("GET", "http://www.example.com/file/example.zip", { //some headers .. }) .then((res) => { // the temp file path - console.log('The file saved to ', res.path()) - }) + console.log("The file saved to ", res.path()); + }); ``` **Set Temp File Extension** @@ -241,71 +259,82 @@ RNFetchBlob 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`. ```js -RNFetchBlob - .config({ - fileCache : true, - // by adding this option, the temp files will have a file extension - appendExt : 'png' - }) - .fetch('GET', 'http://www.example.com/file/example.zip', { +RNFetchBlob.config({ + fileCache: true, + // by adding this option, the temp files will have a file extension + appendExt: "png", +}) + .fetch("GET", "http://www.example.com/file/example.zip", { //some headers .. }) .then((res) => { // the temp file path with file extension `png` - console.log('The file saved to ', res.path()) + console.log("The file saved to ", res.path()); // Beware that when using a file path as Image source on Android, // you must prepend "file://"" before the file path - imageView = - }) + imageView = ( + + ); + }); ``` **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](https://github.com/joltup/rn-fetch-blob/wiki/File-System-Access-API#dirs) in v0.5.0 which represents commonly used directories. +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/joltup/rn-fetch-blob/wiki/File-System-Access-API#dirs) in v0.5.0 which represents commonly used directories. ```js -let dirs = RNFetchBlob.fs.dirs -RNFetchBlob -.config({ +let dirs = RNFetchBlob.fs.dirs; +RNFetchBlob.config({ // response data will be saved to this path if it has access right. - path : dirs.DocumentDir + '/path-to-file.anything' -}) -.fetch('GET', 'http://www.example.com/file/example.zip', { - //some headers .. -}) -.then((res) => { - // the path should be dirs.DocumentDir + 'path-to-file.anything' - console.log('The file saved to ', res.path()) + path: dirs.DocumentDir + "/path-to-file.anything", }) + .fetch("GET", "http://www.example.com/file/example.zip", { + //some headers .. + }) + .then((res) => { + // the path should be dirs.DocumentDir + 'path-to-file.anything' + console.log("The file saved to ", res.path()); + }); ``` **These files won't be removed automatically, please refer to [Cache File Management](#user-content-cache-file-management)** -#### Upload example : Dropbox [files-upload](https://www.dropbox.com/developers/documentation/http/documentation#files-upload) API +#### Upload example : Dropbox [files-upload](https://www.dropbox.com/developers/documentation/http/documentation#files-upload) API `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. ```js - -RNFetchBlob.fetch('POST', 'https://content.dropboxapi.com/2/files/upload', { - Authorization : "Bearer access-token...", - 'Dropbox-API-Arg': JSON.stringify({ - path : '/img-from-react-native.png', - mode : 'add', - autorename : true, - mute : false +RNFetchBlob.fetch( + "POST", + "https://content.dropboxapi.com/2/files/upload", + { + Authorization: "Bearer access-token...", + "Dropbox-API-Arg": JSON.stringify({ + path: "/img-from-react-native.png", + mode: "add", + autorename: true, + mute: false, }), - 'Content-Type' : 'application/octet-stream', + "Content-Type": "application/octet-stream", // here's the body you're going to send, should be a BASE64 encoded string // (you can use "base64"(refer to the library 'mathiasbynens/base64') APIs to make one). // The data will be converted to "byte array"(say, blob) before request sent. - }, base64ImageString) + }, + base64ImageString +) .then((res) => { - console.log(res.text()) + console.log(res.text()); }) .catch((err) => { // error handling .. - }) + }); ``` ### Upload a file from storage @@ -313,25 +342,30 @@ RNFetchBlob.fetch('POST', 'https://content.dropboxapi.com/2/files/upload', { If you're going to use a `file` as request body, just wrap the path with `wrap` API. ```js -RNFetchBlob.fetch('POST', 'https://content.dropboxapi.com/2/files/upload', { +RNFetchBlob.fetch( + "POST", + "https://content.dropboxapi.com/2/files/upload", + { // dropbox upload headers - Authorization : "Bearer access-token...", - 'Dropbox-API-Arg': JSON.stringify({ - path : '/img-from-react-native.png', - mode : 'add', - autorename : true, - mute : false + Authorization: "Bearer access-token...", + "Dropbox-API-Arg": JSON.stringify({ + path: "/img-from-react-native.png", + mode: "add", + autorename: true, + mute: false, }), - 'Content-Type' : 'application/octet-stream', + "Content-Type": "application/octet-stream", // Change BASE64 encoded data to a file path with prefix `RNFetchBlob-file://`. // Or simply wrap the file path with RNFetchBlob.wrap(). - }, RNFetchBlob.wrap(PATH_TO_THE_FILE)) + }, + RNFetchBlob.wrap(PATH_TO_THE_FILE) +) .then((res) => { - console.log(res.text()) + console.log(res.text()); }) .catch((err) => { // error handling .. - }) + }); ``` ### Multipart/form-data example: Post form data with file and data @@ -341,29 +375,48 @@ In `version >= 0.3.0` you can also post files with form data, just put an array Elements have property `filename` will be transformed into binary format, otherwise, it turns into utf8 string. ```js - - RNFetchBlob.fetch('POST', 'http://www.example.com/upload-form', { - Authorization : "Bearer access-token", - otherHeader : "foo", - 'Content-Type' : 'multipart/form-data', - }, [ +RNFetchBlob.fetch( + "POST", + "http://www.example.com/upload-form", + { + Authorization: "Bearer access-token", + otherHeader: "foo", + "Content-Type": "multipart/form-data", + }, + [ // element with property `filename` will be transformed into `file` in form data - { name : 'avatar', filename : 'avatar.png', data: binaryDataInBase64}, + { name: "avatar", filename: "avatar.png", data: binaryDataInBase64 }, // custom content type - { name : 'avatar-png', filename : 'avatar-png.png', type:'image/png', data: binaryDataInBase64}, + { + name: "avatar-png", + filename: "avatar-png.png", + type: "image/png", + data: binaryDataInBase64, + }, // part file from storage - { name : 'avatar-foo', filename : 'avatar-foo.png', type:'image/foo', data: RNFetchBlob.wrap(path_to_a_file)}, + { + name: "avatar-foo", + filename: "avatar-foo.png", + type: "image/foo", + data: RNFetchBlob.wrap(path_to_a_file), + }, // elements without property `filename` will be sent as plain text - { name : 'name', data : 'user'}, - { name : 'info', data : JSON.stringify({ - mail : 'example@example.com', - tel : '12345678' - })}, - ]).then((resp) => { - // ... - }).catch((err) => { + { name: "name", data: "user" }, + { + name: "info", + data: JSON.stringify({ + mail: "example@example.com", + tel: "12345678", + }), + }, + ] +) + .then((resp) => { // ... }) + .catch((err) => { + // ... + }); ``` 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/rn-fetch-blob/issues/94)). @@ -410,48 +463,57 @@ What if you want to append a file to form data? Just like [upload a file from st 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. ```js - RNFetchBlob.fetch('POST', 'http://www.example.com/upload', { - //... some headers, - 'Content-Type' : 'octet-stream' - }, base64DataString) - // listen to upload progress event - .uploadProgress((written, total) => { - console.log('uploaded', written / total) - }) - // listen to download progress event - .progress((received, total) => { - console.log('progress', received / total) - }) - .then((resp) => { - // ... - }) - .catch((err) => { - // ... - }) +RNFetchBlob.fetch( + "POST", + "http://www.example.com/upload", + { + //... some headers, + "Content-Type": "octet-stream", + }, + base64DataString +) + // listen to upload progress event + .uploadProgress((written, total) => { + console.log("uploaded", written / total); + }) + // listen to download progress event + .progress((received, total) => { + console.log("progress", received / total); + }) + .then((resp) => { + // ... + }) + .catch((err) => { + // ... + }); ``` -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. - +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. ```js - RNFetchBlob.fetch('POST', 'http://www.example.com/upload', { - //... some headers, - 'Content-Type' : 'octet-stream' - }, base64DataString) - // listen to upload progress event, emit every 250ms - .uploadProgress({ interval : 250 },(written, total) => { - console.log('uploaded', written / total) - }) - // listen to download progress event, every 10% - .progress({ count : 10 }, (received, total) => { - console.log('progress', received / total) - }) - .then((resp) => { - // ... - }) - .catch((err) => { - // ... - }) +RNFetchBlob.fetch( + "POST", + "http://www.example.com/upload", + { + //... some headers, + "Content-Type": "octet-stream", + }, + base64DataString +) + // listen to upload progress event, emit every 250ms + .uploadProgress({ interval: 250 }, (written, total) => { + console.log("uploaded", written / total); + }) + // listen to download progress event, every 10% + .progress({ count: 10 }, (received, total) => { + console.log("progress", received / total); + }) + .then((resp) => { + // ... + }) + .catch((err) => { + // ... + }); ``` ### Cancel Request @@ -488,20 +550,20 @@ If you want to make a file in `External Storage` becomes visible in Picture, Dow 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. ```js - -RNFetchBlob - .config({ - // DCIMDir is in external storage - path : dirs.DCIMDir + '/music.mp3' - }) - .fetch('GET', 'http://example.com/music.mp3') - .then((res) => RNFetchBlob.fs.scanFile([ { path : res.path(), mime : 'audio/mpeg' } ])) - .then(() => { - // scan file success - }) - .catch((err) => { - // scan file error - }) +RNFetchBlob.config({ + // DCIMDir is in external storage + path: dirs.DCIMDir + "/music.mp3", +}) + .fetch("GET", "http://example.com/music.mp3") + .then((res) => + RNFetchBlob.fs.scanFile([{ path: res.path(), mime: "audio/mpeg" }]) + ) + .then(() => { + // scan file success + }) + .catch((err) => { + // scan file error + }); ``` **Download Manager** @@ -515,23 +577,22 @@ When using DownloadManager, `fileCache` and `path` properties in `config` will n When download complete, DownloadManager will generate a file path so that you can deal with it. ```js -RNFetchBlob - .config({ - addAndroidDownloads : { - useDownloadManager : true, // <-- this is the only thing required - // Optional, override notification setting (default to true) - notification : false, - // Optional, but recommended since android DownloadManager will fail when - // the url does not contains a file extension, by default the mime type will be text/plain - mime : 'text/plain', - description : 'File downloaded by download manager.' - } - }) - .fetch('GET', 'http://example.com/file/somefile') - .then((resp) => { - // the path of downloaded file - resp.path() - }) +RNFetchBlob.config({ + addAndroidDownloads: { + useDownloadManager: true, // <-- this is the only thing required + // Optional, override notification setting (default to true) + notification: false, + // Optional, but recommended since android DownloadManager will fail when + // the url does not contains a file extension, by default the mime type will be text/plain + mime: "text/plain", + description: "File downloaded by download manager.", + }, +}) + .fetch("GET", "http://example.com/file/somefile") + .then((resp) => { + // the path of downloaded file + resp.path(); + }); ``` 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). @@ -541,7 +602,6 @@ Your app might not have right to remove/change the file created by Download Mana - 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`. ```js @@ -571,29 +631,31 @@ This is a new feature added in `0.9.0` if you're going to open a file path using Download and install an APK programmatically ```js - -const android = RNFetchBlob.android +const android = RNFetchBlob.android; RNFetchBlob.config({ - addAndroidDownloads : { - useDownloadManager : true, - title : 'awesome.apk', - description : 'An APK that will be installed', - mime : 'application/vnd.android.package-archive', - mediaScannable : true, - notification : true, - } - }) - .fetch('GET', `http://www.example.com/awesome.apk`) + addAndroidDownloads: { + useDownloadManager: true, + title: "awesome.apk", + description: "An APK that will be installed", + mime: "application/vnd.android.package-archive", + mediaScannable: true, + notification: true, + }, +}) + .fetch("GET", `http://www.example.com/awesome.apk`) .then((res) => { - android.actionViewIntent(res.path(), 'application/vnd.android.package-archive') - }) + android.actionViewIntent( + res.path(), + "application/vnd.android.package-archive" + ); + }); ``` Or show an image in image viewer ```js - android.actionViewIntent(PATH_OF_IMG, 'image/png') +android.actionViewIntent(PATH_OF_IMG, "image/png"); ``` ## File System @@ -605,6 +667,7 @@ File access APIs were made when developing `v0.5.0`, which helping us write test Before start using file APIs, we recommend read [Differences between File Source](https://github.com/joltup/rn-fetch-blob/wiki/File-System-Access-API#differences-between-file-source) first. File Access APIs + - [asset (0.6.2)](https://github.com/joltup/rn-fetch-blob/wiki/File-System-Access-API#assetfilenamestringstring) - [dirs](https://github.com/joltup/rn-fetch-blob/wiki/File-System-Access-API#dirs) - [createFile](https://github.com/joltup/rn-fetch-blob/wiki/File-System-Access-API#createfilepath-data-encodingpromise) @@ -630,7 +693,7 @@ See [File API](https://github.com/joltup/rn-fetch-blob/wiki/File-System-Access-A ### File Stream -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**. +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](#user-content-performance-tips)) @@ -667,56 +730,62 @@ When using `writeStream`, the stream object becomes writable, and you can then p Since version 0.10.9 `write()` resolves with the `RNFetchBlob` instance so you can promise-chain write calls: ```js -RNFetchBlob.fs.writeStream( +RNFetchBlob.fs + .writeStream( PATH_TO_FILE, // encoding, should be one of `base64`, `utf8`, `ascii` - 'utf8', + "utf8", // should data append to existing content ? true -) -.then(ofstream => ofstream.write('foo')) -.then(ofstream => ofstream.write('bar')) -.then(ofstream => ofstream.write('foobar')) -.then(ofstream => ofstream.close()) -.catch(console.error) + ) + .then((ofstream) => ofstream.write("foo")) + .then((ofstream) => ofstream.write("bar")) + .then((ofstream) => ofstream.write("foobar")) + .then((ofstream) => ofstream.close()) + .catch(console.error); ``` or ```js -RNFetchBlob.fs.writeStream( +RNFetchBlob.fs + .writeStream( PATH_TO_FILE, // encoding, should be one of `base64`, `utf8`, `ascii` - 'utf8', + "utf8", // should data append to existing content ? true -) -.then(stream => Promise.all([ - stream.write('foo'), - stream.write('bar'), - stream.write('foobar') -])) -// Use array destructuring to get the stream object from the first item of the array we get from Promise.all() -.then(([stream]) => stream.close()) -.catch(console.error) + ) + .then((stream) => + Promise.all([ + stream.write("foo"), + stream.write("bar"), + stream.write("foobar"), + ]) + ) + // Use array destructuring to get the stream object from the first item of the array we get from Promise.all() + .then(([stream]) => stream.close()) + .catch(console.error); ``` You should **NOT** do something like this: ```js -RNFetchBlob.fs.writeStream( +RNFetchBlob.fs + .writeStream( PATH_TO_FILE, // encoding, should be one of `base64`, `utf8`, `ascii` - 'utf8', + "utf8", // should data append to existing content ? - true) -.then((ofstream) => { + true + ) + .then((ofstream) => { // BAD IDEA - Don't do this, those writes are unchecked: - ofstream.write('foo') - ofstream.write('bar') - ofstream.close() -}) -.catch(console.error) // Cannot catch any write() errors! + ofstream.write("foo"); + ofstream.write("bar"); + ofstream.close(); + }) + .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". @@ -728,22 +797,20 @@ That code may _seem_ to work if there are no errors, but those writes are of the 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 ```js +// remove file using RNFetchblobResponse.flush() object method +RNFetchblob.config({ + fileCache: true, +}) + .fetch("GET", "http://example.com/download/file") + .then((res) => { + // remove cached file from storage + res.flush(); + }); - // remove file using RNFetchblobResponse.flush() object method - RNFetchblob.config({ - fileCache : true - }) - .fetch('GET', 'http://example.com/download/file') - .then((res) => { - // remove cached file from storage - res.flush() - }) - - // remove file by specifying a path - RNFetchBlob.fs.unlink('some-file-path').then(() => { - // ... - }) - +// remove file by specifying a path +RNFetchBlob.fs.unlink("some-file-path").then(() => { + // ... +}); ``` You can also group requests by using `session` API and use `dispose` to remove them all when needed. @@ -785,7 +852,12 @@ You can also group requests by using `session` API and use `dispose` to remove t 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`. ```js -RNFetchBlob.fetch('POST', 'http://example.com/upload', { 'Transfer-Encoding' : 'Chunked' }, bodyData) +RNFetchBlob.fetch( + "POST", + "http://example.com/upload", + { "Transfer-Encoding": "Chunked" }, + bodyData +); ``` ### Self-Signed SSL Server @@ -794,12 +866,12 @@ By default, rn-fetch-blob does NOT allow connection to unknown certification pro ```js RNFetchBlob.config({ - trusty : true -}) -.fetch('GET', 'https://mysite.com') -.then((resp) => { - // ... + trusty: true, }) + .fetch("GET", "https://mysite.com") + .then((resp) => { + // ... + }); ``` ### WiFi only requests @@ -810,17 +882,17 @@ on API version 21 (Lollipop, Android 5.0) or above. APIs below 21 will ignore th ```js RNFetchBlob.config({ - wifiOnly : true -}) -.fetch('GET', 'https://mysite.com') -.then((resp) => { - // ... + wifiOnly: true, }) + .fetch("GET", "https://mysite.com") + .then((resp) => { + // ... + }); ``` ## Web API Polyfills -After `0.8.0` we've made some [Web API polyfills](https://github.com/joltup/rn-fetch-blob/wiki/Web-API-Polyfills-(experimental)) that makes some browser-based library available in RN. +After `0.8.0` we've made some [Web API polyfills]() that makes some browser-based library available in RN. - Blob - XMLHttpRequest (Use our implementation if you're going to use it with Blob) @@ -831,7 +903,7 @@ Here's a [sample app](https://github.com/joltup/rn-firebase-storage-upload-sampl **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. +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** @@ -853,11 +925,11 @@ If you're going to concatenate files, you don't have to read the data to JS cont ## Caveats -* This library does not urlencode unicode characters in URL automatically, see [#146](https://github.com/wkh237/react-native-fetch-blob/issues/146). -* When you create a `Blob` , from an existing file, the file **WILL BE REMOVED** if you `close` the blob. -* 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). -* 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/joltup/rn-fetch-blob/wiki/Fetch-API#fetchprogressconfig-eventlistenerpromisernfetchblobresponse) to limit its frequency. -* When passing a file path to the library, remove `file://` prefix. +- This library does not urlencode unicode characters in URL automatically, see [#146](https://github.com/wkh237/react-native-fetch-blob/issues/146). +- When you create a `Blob` , from an existing file, the file **WILL BE REMOVED** if you `close` the blob. +- 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). +- 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/joltup/rn-fetch-blob/wiki/Fetch-API#fetchprogressconfig-eventlistenerpromisernfetchblobresponse) to limit its frequency. +- When passing a file path to the library, remove `file://` prefix. when you got a problem, have a look at [Trouble Shooting](https://github.com/joltup/rn-fetch-blob/wiki/Trouble-Shooting) or [issues labeled Trouble Shooting](https://github.com/joltup/rn-fetch-blob/issues?utf8=✓&q=label:%22trouble%20shooting%22%20), there'd be some helpful information. diff --git a/react-native.config.js b/react-native.config.js deleted file mode 100644 index 03c61b6ec..000000000 --- a/react-native.config.js +++ /dev/null @@ -1,7 +0,0 @@ -module.exports = { - dependency: { - hooks: { - prelink: 'node ./node_modules/rn-fetch-blob/scripts/prelink.js', - }, - }, -}; diff --git a/scripts/prelink.js b/scripts/prelink.js deleted file mode 100644 index e2c3ac483..000000000 --- a/scripts/prelink.js +++ /dev/null @@ -1,71 +0,0 @@ -try { - var fs = require('fs'); - var glob = require('glob'); - var addAndroidPermissions = process.env.RNFB_ANDROID_PERMISSIONS == 'true'; - var MANIFEST_PATH = glob.sync(process.cwd() + '/android/app/src/main/**/AndroidManifest.xml')[0]; - var PACKAGE_JSON = process.cwd() + '/package.json'; - var package = JSON.parse(fs.readFileSync(PACKAGE_JSON)); - var APP_NAME = package.name; - var PACKAGE_GRADLE = process.cwd() + '/node_modules/rn-fetch-blob/android/build.gradle' - var VERSION = checkVersion(); - - console.log('RNFetchBlob detected app version => ' + VERSION); - - if(VERSION < 0.28) { - console.log('You project version is '+ VERSION + ' which may not compatible to rn-fetch-blob 7.0+, please consider upgrade your application template to react-native 0.27+.') - // add OkHttp3 dependency fo pre 0.28 project - var main = fs.readFileSync(PACKAGE_GRADLE); - console.log('adding OkHttp3 dependency to pre 0.28 project .. ') - main = String(main).replace('//{RNFetchBlob_PRE_0.28_DEPDENDENCY}', "compile 'com.squareup.okhttp3:okhttp:3.4.1'"); - fs.writeFileSync(PACKAGE_GRADLE, main); - console.log('adding OkHttp3 dependency to pre 0.28 project .. ok') - } - - console.log('Add Android permissions => ' + (addAndroidPermissions == "true")) - - if(addAndroidPermissions) { - - // set file access permission for Android < 6.0 - fs.readFile(MANIFEST_PATH, function(err, data) { - - if(err) - console.log('failed to locate AndroidManifest.xml file, you may have to add file access permission manually.'); - else { - - console.log('RNFetchBlob patching AndroidManifest.xml .. '); - // append fs permission - data = String(data).replace( - '', - '\n ' - ) - // append DOWNLOAD_COMPLETE intent permission - data = String(data).replace( - '', - '\n ' - ) - fs.writeFileSync(MANIFEST_PATH, data); - console.log('RNFetchBlob patching AndroidManifest.xml .. ok'); - - } - - }) - } - else { - console.log( - '\033[95mrn-fetch-blob \033[97mwill not automatically add Android permissions after \033[92m0.9.4 '+ - '\033[97mplease run the following command if you want to add default permissions :\n\n' + - '\033[96m\tRNFB_ANDROID_PERMISSIONS=true react-native link \n') - } - - function checkVersion() { - console.log('RNFetchBlob checking app version ..'); - return parseFloat(/\d\.\d+(?=\.)/.exec(package.dependencies['react-native'])); - } - -} catch(err) { - console.log( - '\033[95mrn-fetch-blob\033[97m link \033[91mFAILED \033[97m\nCould not automatically link package :'+ - err.stack + - 'please follow the instructions to manually link the library : ' + - '\033[4mhttps://github.com/joltup/rn-fetch-blob/wiki/Manually-Link-Package\n') -}