base64 Avatar You are not allowed to upload stream files

rn-fetch-blob

release npm npm

A project committed to making file access and information transfer easier and more efficient for React Native developers.

Version Compatibility Alert

rn-fetch-hulk version 0.10.16 is only uniform with react native 0.lx and upward. It should have been a major version bump, we apologize for the mistake. If you are non however upgraded to react native 0.60 or above, yous should remain on rn-fetch-hulk version 0.10.15

Features

  • Transfer information 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
  • File stream support for dealing with large file
  • Blob, File, XMLHttpRequest polyfills that brand browser-based library available in RN (experimental)
  • JSON stream supported base on Oboe.js @jimhigson

TOC (visit Wiki to get the complete documentation)

  • Most
  • Installation
  • HTTP Data Transfer
  • Regular Request
  • Download file
  • Upload file
  • Multipart/class upload
  • Upload/Download progress
  • Abolish HTTP request
  • Android Media Scanner, and Download Manager Support
  • Self-Signed SSL Server
  • Transfer Encoding
  • Drop-in Fetch Replacement
  • File System
  • File admission
  • File stream
  • Manage buried files
  • Web API Polyfills
  • Functioning Tips
  • API References
  • Caveats
  • Evolution

Near

This project was started in the cause of solving consequence facebook/react-native#854, React Native'southward lacks of Hulk implementation which results into bug when transferring binary data.

It is committed to making file access and transfer easier and more than efficient for React Native developers. We've implemented highly customizable filesystem and network module which plays well together. For case, developers can upload and download information directly from/to storage, which is more than efficient, especially for large files. The file system supports file stream, so you don't have to worry virtually 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

Installation

Install package from npm

npm install --salvage rn-fetch-blob

Or if using CocoaPods, add the pod to your Podfile

              pod 'rn-fetch-blob',     :path => '../node_modules/rn-fetch-blob'                          

Afterwards 0.10.3 you lot can install this parcel directly from Github

                              #                replace <branch_name> with whatsoever one of the branches              npm install --salve github:joltup/rn-fetch-blob#<branch_name>            

Manually Link Native Modules

If automatically linking doesn't piece of work for you, see instructions on manually linking.

Automatically Link Native Modules

For 0.29.2+ projects, simply link native packages via the following control (note: rnpm has been merged into react-native)

              react-native link rn-fetch-blob                          

As for projects < 0.29 you demand rnpm to link native packages

Optionally, use the following control to add Android permissions to AndroidManifest.xml automatically

RNFB_ANDROID_PERMISSIONS=true react-native link rn-fetch-blob

pre 0.29 projects

RNFB_ANDROID_PERMISSIONS=true rnpm link

The link script might not take effect if yous take non-default project structure, please visit the wiki to link the parcel manually.

Grant Permission to External storage for Android 5.0 or lower

The mechanism for granting Android permissions has slightly unlike since Android half dozen.0 released, please refer to Official Document.

If you're going to admission external storage (say, SD bill of fare storage) for Android five.0 (or lower) devices, you might have to add the following line to AndroidManifest.xml.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.rnfetchblobtest"     android:versionCode="1"     android:versionName="1.0">      <uses-permission android:proper name="android.permission.INTERNET" />     <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>                              +                <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />                              +                <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />                              +                <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />              ...            

Likewise, if you're going to utilize Android Download Manager you have to add together this to AndroidManifest.xml

              <intent-filter>             <action android:proper noun="android.intent.action.Primary" />             <category android:proper name="android.intent.category.LAUNCHER" />                              +                <activity android:name="android.intent.action.DOWNLOAD_COMPLETE"/>              </intent-filter>

If you lot are going to utilize the wifiOnly flag, you need to add this to AndroidManifest.xml

                              +                <uses-permission android:proper noun="android.permission.ACCESS_NETWORK_STATE" />              ...            

Grant Access Permission for Android six.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 employ PermissionAndroid API.

Usage

ES6

The module uses ES6 style export statement, but utilize import to load the module.

              import              RNFetchBlob              from              'rn-fetch-blob'            

ES5

If you lot're using ES5 require statement to load the module, please add default. See hither for more particular.

              var RNFetchBlob = require('rn-fetch-hulk').default                          

HTTP Data Transfer

Regular Request

Later 0.8.0 rn-fetch-blob automatically decides how to send the body by checking its blazon and Content-Type in the header. The rule is described in the following diagram

To sum up:

  • To send a form data, the Content-Blazon 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, utilise BASE64 encoded string or path points to a file contains the body.
  • If the Content-Blazon containing substring;BASE64 or application/octet the given body volition be considered as a BASE64 encoded data which volition be decoded to binary data as the request body.
  • Otherwise, if a string starts with RNFetchBlob-file:// (which can only be done past RNFetchBlob.wrap(PATH_TO_THE_FILE)), it will endeavor to detect the data from the URI string afterward RNFetchBlob-file:// and use information technology as the request torso.
  • To ship the torso as-is, only utilize a Content-Type header not containing ;BASE64 or application/octet.

It is Worth to mentioning that the HTTP request uses enshroud by default, if y'all're going to disable it but add a Cache-Command header 'Cache-Control' : 'no-shop'

Later on 0.9.four, we disabled Chunked transfer encoding by default, if you're going to use it, you should explicitly set header Transfer-Encoding to Chunked.

Download example: Fetch files that need dominance token

Most simple way is download to memory and stored every bit BASE64 encoded string, this is handy when the response data is small-scale. Notation that when it comes to authorization, not only can you lot use an authority token, merely this package will automatically pass the cookies created past normal js requests such equally axios and fetch. Therefore, if you are using traditional cookie-based means to authorize your user, yous don't demand to do anything before this package works.

              // send http asking in a new thread (using native code)              RNFetchBlob              .              fetch              (              'Get'              ,              'http://www.case.com/images/img1.png'              ,              {              Authorization              :              'Bearer admission-token...'              ,              // more than headers  ..              }              )              .              then              (              (              res              )              =>              {              let              status              =              res              .              info              (              )              .              status              ;              if              (              status              ==              200              )              {              // the conversion is washed in native lawmaking              let              base64Str              =              res              .              base64              (              )              // the following conversions are done in js, it's SYNC              let              text              =              res              .              text              (              )              allow              json              =              res              .              json              (              )              }              else              {              // handle other condition codes              }              }              )              // Something went wrong:              .              catch              (              (              errorMessage              ,              statusCode              )              =>              {              // error handling              }              )            

Download to storage directly

If the response data is large, that would be a bad idea to convert it into BASE64 string. A amend solution is streaming the response directly into a file, simply add together a fileCache selection to config, and ready it to true. This will make incoming response information stored in a temporary path without whatsoever file extension.

These files won't be removed automatically, please refer to Cache File Management

              RNFetchBlob              .              config              (              {              // add this option that makes response data to be stored every bit a file,              // this is much more performant.              fileCache              :              true              ,              }              )              .              fetch              (              'GET'              ,              'http://world wide web.instance.com/file/example.zip'              ,              {              //some headers ..              }              )              .              then              (              (              res              )              =>              {              // the temp file path              console              .              log              (              'The file saved to '              ,              res              .              path              (              )              )              }              )            

Ready Temp File Extension

Sometimes yous might need a file extension for some reason. For case, when using file path as the source of Image component, the path should end with something like .png or .jpg, you can practice this past add together appendExt option to config.

              RNFetchBlob              .              config              (              {              fileCache              :              true              ,              // past adding this option, the temp files will accept a file extension              appendExt              :              'png'              }              )              .              fetch              (              'Go'              ,              '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              (              )              )              // Beware that when using a file path every bit Prototype source on Android,              // you must prepend "file://"" before the file path              imageView              =              <              Image              source              =              {              {              uri              :              Platform              .              OS              ===              'android'              ?              'file://'              +              res              .              path              (              )              :              ''              +              res              .              path              (              )              }              }              /              >              }              )            

Use Specific File Path

If you lot prefer a detail file path rather than randomly generated one, y'all tin can utilise path option. We've added several constants in v0.5.0 which represents usually used directories.

              let              dirs              =              RNFetchBlob              .              fs              .              dirs              RNFetchBlob              .              config              (              {              // response information volition be saved to this path if it has access right.              path              :              dirs              .              DocumentDir              +              '/path-to-file.anything'              }              )              .              fetch              (              'Get'              ,              'http://world wide web.example.com/file/example.cypher'              ,              {              //some headers ..              }              )              .              then              (              (              res              )              =>              {              // the path should exist dirs.DocumentDir + 'path-to-file.annihilation'              console              .              log              (              'The file saved to '              ,              res              .              path              (              )              )              }              )            

These files won't be removed automatically, please refer to Enshroud File Management

Upload instance : Dropbox files-upload API

rn-fetch-blob will convert the base64 string in body to binary format using native API, this process is washed in a separated thread so that it won't block your GUI.

              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'              ,              style              :              'add'              ,              autorename              :              true              ,              mute              :              fake              }              )              ,              'Content-Blazon'              :              'application/octet-stream'              ,              // here'southward the body y'all're going to transport, should be a BASE64 encoded string              // (you can utilize "base64"(refer to the library 'mathiasbynens/base64') APIs to make one).              // The data volition be converted to "byte assortment"(say, hulk) earlier request sent.              }              ,              base64ImageString              )              .              then              (              (              res              )              =>              {              console              .              log              (              res              .              text              (              )              )              }              )              .              take hold of              (              (              err              )              =>              {              // error handling ..              }              )            

Upload a file from storage

If y'all're going to utilize a file as request body, merely wrap the path with wrap API.

              RNFetchBlob              .              fetch              (              'POST'              ,              'https://content.dropboxapi.com/2/files/upload'              ,              {              // dropbox upload headers              Dominance              :              "Bearer admission-token..."              ,              'Dropbox-API-Arg':              JSON              .              stringify              (              {              path              :              '/img-from-react-native.png'              ,              style              :              'add'              ,              autorename              :              true              ,              mute              :              imitation              }              )              ,              'Content-Type'              :              'application/octet-stream'              ,              // Change BASE64 encoded data to a file path with prefix `RNFetchBlob-file://`.              // Or just wrap the file path with RNFetchBlob.wrap().              }              ,              RNFetchBlob              .              wrap              (              PATH_TO_THE_FILE              )              )              .              and so              (              (              res              )              =>              {              panel              .              log              (              res              .              text              (              )              )              }              )              .              catch              (              (              err              )              =>              {              // fault handling ..              }              )            

Multipart/form-data case: Mail form data with file and data

In version >= 0.3.0 you can also postal service files with form information, simply put an assortment in body, with elements have property name, data, and filename(optional).

Elements have belongings filename will be transformed into binary format, otherwise, it turns into utf8 string.

              RNFetchBlob              .              fetch              (              'Mail'              ,              'http://world wide web.example.com/upload-class'              ,              {              Authorization              :              "Bearer admission-token"              ,              otherHeader              :              "foo"              ,              'Content-Type'              :              'multipart/form-data'              ,              }              ,              [              // element with holding `filename` will exist transformed into `file` in form information              {              name              :              'avatar'              ,              filename              :              'avatar.png'              ,              information:              binaryDataInBase64              }              ,              // custom content type              {              proper name              :              'avatar-png'              ,              filename              :              'avatar-png.png'              ,              type:'image/png'              ,              data:              binaryDataInBase64              }              ,              // role file from storage              {              name              :              'avatar-foo'              ,              filename              :              'avatar-foo.png'              ,              type:'image/foo'              ,              information:              RNFetchBlob              .              wrap              (              path_to_a_file              )              }              ,              // elements without property `filename` will be sent equally obviously text              {              proper noun              :              'name'              ,              data              :              'user'              }              ,              {              proper name              :              'info'              ,              information              :              JSON              .              stringify              (              {              mail service              :              'example@example.com'              ,              tel              :              '12345678'              }              )              }              ,              ]              )              .              and then              (              (              resp              )              =>              {              // ...              }              )              .              catch              (              (              err              )              =>              {              // ...              }              )            

What if you want to append a file to form data? Merely like upload a file from storage example, wrap data by wrap API (this characteristic is only bachelor for version >= v0.five.0). On version >= 0.6.2, it is possible to set custom MIME type when appending a file to course data. Only go along in mind when the file is big it's likely to crash your app. Please consider utilize other strategy (see #94).

              RNFetchBlob              .              fetch              (              'POST'              ,              'http://www.example.com/upload-course'              ,              {              Potency              :              "Bearer access-token"              ,              otherHeader              :              "foo"              ,              // this is required, otherwise information technology won't be process as a multipart/class-data request              'Content-Type'              :              'multipart/form-data'              ,              }              ,              [              // append field data from file path              {              name              :              'avatar'              ,              filename              :              'avatar.png'              ,              // Change BASE64 encoded information to a file path with prefix `RNFetchBlob-file://`.              // Or merely wrap the file path with RNFetchBlob.wrap().              information:              RNFetchBlob              .              wrap              (              PATH_TO_THE_FILE              )              }              ,              {              name              :              'ringtone'              ,              filename              :              'ring.mp3'              ,              // utilise custom MIME blazon              blazon              :              'application/mp3'              ,              // upload a file from asset is also possible in version >= 0.half dozen.two              data              :              RNFetchBlob              .              wrap              (              RNFetchBlob              .              fs              .              asset              (              'default-ringtone.mp3'              )              )              }              // elements without property `filename` will be sent as plain text              {              name              :              'name'              ,              data              :              'user'              }              ,              {              name              :              'info'              ,              information              :              JSON              .              stringify              (              {              mail              :              'example@example.com'              ,              tel              :              '12345678'              }              )              }              ,              ]              )              .              so              (              (              resp              )              =>              {              // ...              }              )              .              catch              (              (              err              )              =>              {              // ...              }              )            

Upload/Download progress

In version >= 0.4.2 information technology is possible to know the upload/download progress. After 0.7.0 IOS and Android upload progress are besides supported.

              RNFetchBlob              .              fetch              (              'Mail'              ,              'http://www.example.com/upload'              ,              {              //... some headers,              'Content-Type'              :              'octet-stream'              }              ,              base64DataString              )              // listen to upload progress result              .              uploadProgress              (              (              written              ,              total              )              =>              {              panel              .              log              (              'uploaded'              ,              written              /              total              )              }              )              // listen to download progress upshot              .              progress              (              (              received              ,              total              )              =>              {              console              .              log              (              'progress'              ,              received              /              full              )              }              )              .              then              (              (              resp              )              =>              {              // ...              }              )              .              catch              (              (              err              )              =>              {              // ...              }              )            

In 0.9.6, you can specify an object as the get-go argument which contains count and interval, to the frequency of progress upshot (this will be washed 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.

              RNFetchBlob              .              fetch              (              'Post'              ,              'http://world wide web.instance.com/upload'              ,              {              //... some headers,              'Content-Type'              :              'octet-stream'              }              ,              base64DataString              )              // listen to upload progress consequence, emit every 250ms              .              uploadProgress              (              {              interval              :              250              }              ,              (              written              ,              total              )              =>              {              panel              .              log              (              'uploaded'              ,              written              /              total              )              }              )              // listen to download progress issue, every 10%              .              progress              (              {              count              :              ten              }              ,              (              received              ,              total              )              =>              {              panel              .              log              (              'progress'              ,              received              /              total              )              }              )              .              then              (              (              resp              )              =>              {              // ...              }              )              .              catch              (              (              err              )              =>              {              // ...              }              )            

Cancel Request

After 0.7.0 it is possible to cancel an HTTP request. Upon cancellation, information technology throws a promise rejection, be certain to catch information technology.

              allow              chore              =              RNFetchBlob              .              fetch              (              'GET'              ,              'http://example.com/file/1'              )              job              .              then              (              (              )              =>              {              ...              }              )              // handle request cancelled rejection              .              grab              (              (              err              )              =>              {              panel              .              log              (              err              )              }              )              // abolish the request, the callback function is optional              task              .              cancel              (              (              err              )              =>              {              ...              }              )            

Driblet-in Fetch Replacement

0.9.0

If yous have existing code that uses whatwg-fetch(the official fetch), information technology'southward not necessary to supervene upon them with RNFetchblob.fetch, yous can simply use our Fetch Replacement. The deviation between Official them is official fetch uses whatwg-fetch which wraps XMLHttpRequest polyfill under the hood. Information technology's a great library for spider web developers, only does non play very well with RN. Our implementation is simply a wrapper of our fetch and fs APIs, so y'all can admission all the features we provided.

Run across document and examples

Android Media Scanner, and Download Managing director Support

If you want to make a file in External Storage becomes visible in Motion-picture show, Downloads, or other congenital-in apps, you lot 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 volition try to resolve the file using its file extension.

              RNFetchBlob              .              config              (              {              // DCIMDir is in external storage              path              :              dirs              .              DCIMDir              +              '/music.mp3'              }              )              .              fetch              (              'Go'              ,              'http://example.com/music.mp3'              )              .              then              (              (              res              )              =>              RNFetchBlob              .              fs              .              scanFile              (              [              {              path              :              res              .              path              (              )              ,              mime              :              'audio/mpeg'              }              ]              )              )              .              and then              (              (              )              =>              {              // scan file success              }              )              .              catch              (              (              err              )              =>              {              // scan file error              }              )            

Download Manager

When downloading big files on Android it is recommended to use Download Director, it supports a lot of native features like the progress bar, and notification, also the download chore will exist handled by OS, and more than efficient.

When using DownloadManager, fileCache and path backdrop in config will non take event, considering Android DownloadManager tin only store files to external storage, also discover that Download Manager tin can simply support Go method, which ways the request body will be ignored.

When download complete, DownloadManager will generate a file path so that you tin can deal with it.

              RNFetchBlob              .              config              (              {              addAndroidDownloads              :              {              useDownloadManager              :              true              ,              // <-- this is the merely thing required              // Optional, override notification setting (default to true)              notification              :              fake              ,              // 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/manifestly              mime              :              'text/plain'              ,              clarification              :              'File downloaded by download director.'              }              }              )              .              fetch              (              'Go'              ,              'http://example.com/file/somefile'              )              .              then              (              (              resp              )              =>              {              // the path of downloaded file              resp              .              path              (              )              }              )            

Your app might not take right to remove/change the file created by Download Manager, therefore you might demand to set custom location to the download task.

Download Notification and Visibility in Download App (Android Merely)

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 together some options to config.

              RNFetchBlob              .              config              (              {              fileCache              :              truthful              ,              // android but options, these options be a no-op on IOS              addAndroidDownloads              :              {              // Show notification when response information transmitted              notification              :              truthful              ,              // Championship of download notification              championship              :              'Cracking ! Download Success ! :O '              ,              // File description (non notification clarification)              description              :              'An image file.'              ,              mime              :              'image/png'              ,              // Make the file scannable  by media scanner              mediaScannable              :              true              ,              }              }              )              .              fetch              (              'GET'              ,              'http://example.com/image1.png'              )              .              and then              (...)            

Open up Downloaded File with Intent

This is a new feature added in 0.9.0 if you're going to open up a file path using official Linking API that might non work every bit expected, besides, if you're going to install an APK in Downloads app, that volition not office besides. As an alternative, you tin can endeavor actionViewIntent API, which will send an ACTION_VIEW intent for y'all which uses the given MIME type.

Download and install an APK programmatically

              const              android              =              RNFetchBlob              .              android              RNFetchBlob              .              config              (              {              addAndroidDownloads              :              {              useDownloadManager              :              true              ,              title              :              'awesome.apk'              ,              clarification              :              'An APK that will be installed'              ,              mime              :              'application/vnd.android.packet-archive'              ,              mediaScannable              :              true              ,              notification              :              true              ,              }              }              )              .              fetch              (              'Become'              ,              `http://www.instance.com/awesome.apk`              )              .              then              (              (              res              )              =>              {              android              .              actionViewIntent              (              res              .              path              (              )              ,              'awarding/vnd.android.package-archive'              )              }              )            

Or testify an image in image viewer

              android              .              actionViewIntent              (              PATH_OF_IMG              ,              'prototype/png'              )            

File System

File Access

File access APIs were made when developing v0.5.0, which helping united states write tests, and was not planned to be a function of this module. All the same, we realized that it's difficult to detect a cracking solution to manage cached files, anybody who uses this module may need these APIs for their cases.

Before start using file APIs, we recommend read Differences between File Source get-go.

File Access APIs

  • asset (0.6.2)
  • dirs
  • createFile
  • writeFile (0.6.0)
  • appendFile (0.six.0)
  • readFile (0.six.0)
  • readStream
  • hash (0.10.nine)
  • writeStream
  • hash
  • unlink
  • mkdir
  • ls
  • mv
  • cp
  • exists
  • isDir
  • stat
  • lstat
  • scanFile (Android only)

Come across File API for more data

File Stream

In v0.v.0 nosotros'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 information into BASE64 encoded cord. Information technology'south handy when processing large files.

When calling readStream method, yous have to open the stream, and commencement to read information. When the file is large, consider using an appropriate bufferSize and interval to reduce the native event dispatching overhead (run into Performance Tips)

The file stream event has a default throttle(10ms) and buffer size which preventing it crusade too much overhead to main thread, yo can also tweak these values.

              let              data              =              ''              RNFetchBlob              .              fs              .              readStream              (              // file path              PATH_TO_THE_FILE              ,              // encoding, should be one of `base64`, `utf8`, `ascii`              'base64'              ,              // (optional) buffer size, default to 4096 (4095 for BASE64 encoded data)              // when reading file in BASE64 encoding, buffer size must exist multiples of 3.              4095              )              .              so              (              (              ifstream              )              =>              {              ifstream              .              open              (              )              ifstream              .              onData              (              (              clamper              )              =>              {              // when encoding is `ascii`, chunk will be an assortment contains numbers              // otherwise it will exist a string              data              +=              chunk              }              )              ifstream              .              onError              (              (              err              )              =>              {              panel              .              log              (              'oops'              ,              err              )              }              )              ifstream              .              onEnd              (              (              )              =>              {              <              Paradigm              source              =              {              {              uri              :              'information:image/png,base64'              +              information              }              }              }              )              }              )            

When using writeStream, the stream object becomes writable, and you can and so perform operations similar write and shut.

Since version 0.10.9 write() resolves with the RNFetchBlob instance then y'all can promise-chain write calls:

              RNFetchBlob              .              fs              .              writeStream              (              PATH_TO_FILE              ,              // encoding, should be one of `base64`, `utf8`, `ascii`              'utf8'              ,              // should data append to existing content ?              true              )              .              then              (              ofstream              =>              ofstream              .              write              (              'foo'              )              )              .              and then              (              ofstream              =>              ofstream              .              write              (              'bar'              )              )              .              then              (              ofstream              =>              ofstream              .              write              (              'foobar'              )              )              .              so              (              ofstream              =>              ofstream              .              close              (              )              )              .              catch              (              console              .              mistake              )            

or

              RNFetchBlob              .              fs              .              writeStream              (              PATH_TO_FILE              ,              // encoding, should be one of `base64`, `utf8`, `ascii`              'utf8'              ,              // should information suspend to existing content ?              true              )              .              then              (              stream              =>              Hope              .              all              (              [              stream              .              write              (              'foo'              )              ,              stream              .              write              (              'bar'              )              ,              stream              .              write              (              'foobar'              )              ]              )              )              // Apply array destructuring to get the stream object from the first item of the assortment we get from Promise.all()              .              so              (              (              [              stream              ]              )              =>              stream              .              shut              (              )              )              .              grab              (              panel              .              error              )            

You lot should Non practice something like this:

              RNFetchBlob              .              fs              .              writeStream              (              PATH_TO_FILE              ,              // encoding, should be one of `base64`, `utf8`, `ascii`              'utf8'              ,              // should data append to existing content ?              true              )              .              then              (              (              ofstream              )              =>              {              // BAD IDEA - Don't do this, those writes are unchecked:              ofstream              .              write              (              'foo'              )              ofstream              .              write              (              'bar'              )              ofstream              .              shut              (              )              }              )              .              catch              (              console              .              error              )              // Cannot catch any write() errors!            

The problem with the above lawmaking is that the promises from the ofstream.write() calls are detached and "Lost". That ways the entire promise chain A) resolves without waiting for the writes to terminate and B) whatsoever errors caused by them are lost. That code may seem to work if in that location are no errors, but those writes are of the type "burn and forget": You start them and then turn abroad and never know if they actually succeeded.

Enshroud File Management

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. At that place're several ways to remove the files

              // remove file using RNFetchblobResponse.flush() object method              RNFetchblob              .              config              (              {              fileCache              :              truthful              }              )              .              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              (              (              )              =>              {              // ...              }              )            

You tin can too group requests by using session API and use dispose to remove them all when needed.

              RNFetchblob              .              config              (              {              fileCache              :              true              }              )              .              fetch              (              'Go'              ,              'http://instance.com/download/file'              )              .              then              (              (              res              )              =>              {              // set session of a response              res              .              session              (              'foo'              )              }              )              RNFetchblob              .              config              (              {              // you tin can also set session beforehand              session              :              'foo'              fileCache              :              true              }              )              .              fetch              (              'GET'              ,              'http://instance.com/download/file'              )              .              then              (              (              res              )              =>              {              // ...              }              )              // or put an existing file path to the session              RNFetchBlob              .              session              (              'foo'              )              .              add              (              'some-file-path'              )              // remove a file path from the session              RNFetchBlob              .              session              (              'foo'              )              .              remove              (              'some-file-path'              )              // list paths of a session              RNFetchBlob              .              session              (              'foo'              )              .              list              (              )              // remove all files in a session              RNFetchBlob              .              session              (              'foo'              )              .              dispose              (              )              .              then              (              (              )              =>              {              ...              }              )            

Transfer Encoding

Afterwards 0.nine.4, the Chunked transfer encoding is disabled by default due to some service provider may not support chunked transfer. To enable it, prepare Transfer-Encoding header to Chunked.

              RNFetchBlob              .              fetch              (              'Post'              ,              'http://example.com/upload'              ,              {              'Transfer-Encoding'              :              'Chunked'              }              ,              bodyData              )            

Self-Signed SSL Server

By default, rn-fetch-hulk does NOT allow connexion to unknown certification provider since it'south dangerous. To connect a server with cocky-signed certification, you need to add trusty to config explicitly. This function is available for version >= 0.5.3

              RNFetchBlob              .              config              (              {              trusty              :              true              }              )              .              fetch              (              'Become'              ,              'https://mysite.com'              )              .              and then              (              (              resp              )              =>              {              // ...              }              )            

WiFi only requests

If yous wish to only road requests through the Wifi interface, set the below configuration. Note: On Android, the ACCESS_NETWORK_STATE permission must be fix, and this flag volition only piece of work on API version 21 (Lollipop, Android 5.0) or higher up. APIs below 21 will ignore this flag.

              RNFetchBlob              .              config              (              {              wifiOnly              :              true              }              )              .              fetch              (              'Get'              ,              'https://mysite.com'              )              .              then              (              (              resp              )              =>              {              // ...              }              )            

Web API Polyfills

After 0.8.0 we've fabricated some Web API polyfills that makes some browser-based library available in RN.

  • Blob
  • XMLHttpRequest (Utilize our implementation if you're going to use information technology with Hulk)

Here's a sample app that uses polyfills to upload files to FireBase.

Performance Tips

Read Stream and Progress Event Overhead

If the process seems to block JS thread when file is big when reading data via fs.readStream. Information technology 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 (bachelor 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 information before they sent to each side. When data is large, this will be quite a performance impact to your app. Information technology'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 cord 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. Apply 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 y'all're going to concatenate files, you don't take to read the data to JS context anymore! In 0.viii.0 we introduced new encoding uri for writeFile and appendFile API, which go far possible to handle the whole process in native.

Caveats

  • This library does not urlencode unicode characters in URL automatically, see #146.
  • When you create a Blob , from an existing file, the file WILL Exist REMOVED if you shut the blob.
  • If you replaced window.XMLHttpRequest for some reason (e.g. make Firebase SDK work), it will also touch on how official fetch works (basically information technology should piece of work just fine).
  • When file stream and upload/download progress event tedious down your app, consider an upgrade to 0.nine.6+, utilise boosted arguments to limit its frequency.
  • When passing a file path to the library, remove file:// prefix.

when you got a problem, take a look at Trouble Shooting or bug labeled Problem Shooting, in that location'd be some helpful data.

Changes

Meet release notes

Development

If yous're interested in hacking this module, check our development guide, there might be some helpful data. Please feel free to make a PR or file an effect.

phillipsristraid1999.blogspot.com

Source: https://github.com/joltup/rn-fetch-blob

0 Response to "base64 Avatar You are not allowed to upload stream files"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel