Upload Image as Byte Array of Hash

rn-fetch-hulk

release npm npm

A projection committed to making file access and data transfer easier and more than efficient for React Native developers.

Version Compatibility Warning

rn-fetch-blob version 0.10.xvi is only compatible with react native 0.lx and up. It should have been a major version bump, we apologize for the error. If yous are not yet upgraded to react native 0.60 or to a higher place, you lot should remain on rn-fetch-hulk 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
  • File stream support for dealing with big file
  • Blob, File, XMLHttpRequest polyfills that make browser-based library bachelor in RN (experimental)
  • JSON stream supported base of operations on Oboe.js @jimhigson

TOC (visit Wiki to get the complete documentation)

  • About
  • Installation
  • HTTP Data Transfer
  • Regular Request
  • Download file
  • Upload file
  • Multipart/form upload
  • Upload/Download progress
  • Cancel HTTP request
  • Android Media Scanner, and Download Manager Support
  • Cocky-Signed SSL Server
  • Transfer Encoding
  • Drib-in Fetch Replacement
  • File System
  • File admission
  • File stream
  • Manage buried files
  • Web API Polyfills
  • Performance Tips
  • API References
  • Caveats
  • Development

About

This projection was started in the cause of solving upshot facebook/react-native#854, React Native'southward lacks of Blob implementation which results into problems when transferring binary data.

It is committed to making file admission and transfer easier and more efficient for React Native developers. We've implemented highly customizable filesystem and network module which plays well together. For case, developers tin upload and download data directly from/to storage, which is more efficient, particularly for large files. The file system supports file stream, and so yous don't have to worry about OOM problem when accessing large files.

In 0.viii.0 we introduced experimental Web API polyfills that go far possible to use browser-based libraries in React Native, such equally, FireBase JS SDK

Installation

Install package from npm

npm install --relieve rn-fetch-blob

Or if using CocoaPods, add the pod to your Podfile

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

After 0.x.3 you can install this bundle direct from Github

                              #                replace <branch_name> with any one of the branches              npm install --save github:joltup/rn-fetch-hulk#<branch_name>            

Manually Link Native Modules

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

Automatically Link Native Modules

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

              react-native link rn-fetch-blob                          

Equally for projects < 0.29 you need rnpm to link native packages

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

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

pre 0.29 projects

RNFB_ANDROID_PERMISSIONS=true rnpm link

The link script might not take event if you have non-default projection structure, delight visit the wiki to link the package manually.

Grant Permission to External storage for Android 5.0 or lower

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

If you're going to access external storage (say, SD card storage) for Android 5.0 (or lower) devices, y'all might have to add the post-obit line to AndroidManifest.xml.

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

Likewise, if you're going to employ Android Download Managing director yous accept to add this to AndroidManifest.xml

              <intent-filter>             <action android:name="android.intent.activeness.Chief" />             <category android:proper name="android.intent.category.LAUNCHER" />                              +                <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>              </intent-filter>

If you are going to use the wifiOnly flag, yous need to add this to AndroidManifest.xml

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

Grant Access Permission for Android 6.0

Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, non when they install the app. So adding permissions in AndroidManifest.xml won't piece of work for Android 6.0+ devices. To grant permissions in runtime, y'all might apply PermissionAndroid API.

Usage

ES6

The module uses ES6 manner export statement, only use import to load the module.

              import              RNFetchBlob              from              'rn-fetch-blob'            

ES5

If y'all're using ES5 require statement to load the module, please add together default. Meet hither for more detail.

              var RNFetchBlob = crave('rn-fetch-blob').default                          

HTTP Data Transfer

Regular Request

After 0.eight.0 rn-fetch-blob automatically decides how to send the body by checking its type and Content-Type in the header. The rule is described in the following diagram

To sum upward:

  • To send a form information, the Content-Type header does not matter. When the body is an Assortment we will set proper content type for yous.
  • To transport binary data, you have 2 choices, use 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 will be considered as a BASE64 encoded data which will be decoded to binary information as the request body.
  • Otherwise, if a cord starts with RNFetchBlob-file:// (which tin can just be done by RNFetchBlob.wrap(PATH_TO_THE_FILE)), it will try to observe the data from the URI string after RNFetchBlob-file:// and use it equally the asking torso.
  • To send the trunk every bit-is, just apply a Content-Type header not containing ;BASE64 or awarding/octet.

It is Worth to mentioning that the HTTP request uses cache past default, if you're going to disable it only add a Cache-Command header 'Cache-Command' : 'no-shop'

Afterward 0.9.4, we disabled Chunked transfer encoding by default, if you're going to utilise it, you should explicitly set header Transfer-Encoding to Chunked.

Download case: Fetch files that need authorization token

Most uncomplicated way is download to retentivity and stored equally BASE64 encoded string, this is handy when the response data is small. Note that when it comes to authorization, non just can you utilise an say-so token, merely this packet will automatically pass the cookies created by normal js requests such as axios and fetch. Therefore, if y'all are using traditional cookie-based ways to authorize your user, you don't need to do annihilation before this package works.

              // 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 than headers  ..              }              )              .              and then              (              (              res              )              =>              {              let              condition              =              res              .              info              (              )              .              condition              ;              if              (              condition              ==              200              )              {              // the conversion is done in native code              let              base64Str              =              res              .              base64              (              )              // the post-obit conversions are washed in js, it's SYNC              let              text              =              res              .              text              (              )              let              json              =              res              .              json              (              )              }              else              {              // handle other condition codes              }              }              )              // Something went incorrect:              .              catch              (              (              errorMessage              ,              statusCode              )              =>              {              // mistake treatment              }              )            

Download to storage straight

If the response data is large, that would be a bad idea to convert it into BASE64 string. A better solution is streaming the response directly into a file, simply add together a fileCache option to config, and set it to truthful. This volition make incoming response data stored in a temporary path without any file extension.

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

              RNFetchBlob              .              config              (              {              // add this pick that makes response data to be stored every bit a file,              // this is much more performant.              fileCache              :              true              ,              }              )              .              fetch              (              'Get'              ,              'http://www.case.com/file/instance.zippo'              ,              {              //some headers ..              }              )              .              and so              (              (              res              )              =>              {              // the temp file path              console              .              log              (              'The file saved to '              ,              res              .              path              (              )              )              }              )            

Prepare Temp File Extension

Sometimes you might need a file extension for some reason. For example, when using file path as the source of Image component, the path should end with something similar .png or .jpg, you tin do this by add appendExt option to config.

              RNFetchBlob              .              config              (              {              fileCache              :              true              ,              // past adding this option, the temp files volition 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              (              )              )              // Beware that when using a file path as Image source on Android,              // you must prepend "file://"" before the file path              imageView              =              <              Image              source              =              {              {              uri              :              Platform              .              Bone              ===              'android'              ?              'file://'              +              res              .              path              (              )              :              ''              +              res              .              path              (              )              }              }              /              >              }              )            

Utilize Specific File Path

If you prefer a particular file path rather than randomly generated one, you tin can utilise path option. We've added several constants in v0.v.0 which represents ordinarily used directories.

              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'              panel              .              log              (              'The file saved to '              ,              res              .              path              (              )              )              }              )            

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

Upload example : Dropbox files-upload API

rn-fetch-hulk 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'              ,              {              Authority              :              "Bearer admission-token..."              ,              'Dropbox-API-Arg':              JSON              .              stringify              (              {              path              :              '/img-from-react-native.png'              ,              mode              :              'add'              ,              autorename              :              true              ,              mute              :              false              }              )              ,              'Content-Type'              :              'application/octet-stream'              ,              // hither's the body you're going to transport, should exist a BASE64 encoded cord              // (you tin utilize "base64"(refer to the library 'mathiasbynens/base64') APIs to brand one).              // The data will be converted to "byte assortment"(say, blob) earlier request sent.              }              ,              base64ImageString              )              .              then              (              (              res              )              =>              {              panel              .              log              (              res              .              text              (              )              )              }              )              .              catch              (              (              err              )              =>              {              // error handling ..              }              )            

Upload a file from storage

If you're going to utilise a file every bit request body, just wrap the path with wrap API.

              RNFetchBlob              .              fetch              (              'POST'              ,              'https://content.dropboxapi.com/2/files/upload'              ,              {              // dropbox upload headers              Authorization              :              "Bearer admission-token..."              ,              'Dropbox-API-Arg':              JSON              .              stringify              (              {              path              :              '/img-from-react-native.png'              ,              manner              :              'add together'              ,              autorename              :              true              ,              mute              :              false              }              )              ,              'Content-Type'              :              'application/octet-stream'              ,              // Alter 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              )              )              .              so              (              (              res              )              =>              {              console              .              log              (              res              .              text              (              )              )              }              )              .              take hold of              (              (              err              )              =>              {              // fault handling ..              }              )            

Multipart/form-information example: Mail form data with file and information

In version >= 0.3.0 y'all can as well post files with form data, just put an array in body, with elements have holding proper noun, data, and filename(optional).

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

              RNFetchBlob              .              fetch              (              'POST'              ,              'http://www.example.com/upload-class'              ,              {              Authorization              :              "Bearer access-token"              ,              otherHeader              :              "foo"              ,              'Content-Blazon'              :              'multipart/form-data'              ,              }              ,              [              // element with holding `filename` will be transformed into `file` in form data              {              name              :              'avatar'              ,              filename              :              'avatar.png'              ,              information:              binaryDataInBase64              }              ,              // custom content type              {              name              :              'avatar-png'              ,              filename              :              'avatar-png.png'              ,              type:'image/png'              ,              information:              binaryDataInBase64              }              ,              // part file from storage              {              name              :              'avatar-foo'              ,              filename              :              'avatar-foo.png'              ,              blazon:'prototype/foo'              ,              data:              RNFetchBlob              .              wrap              (              path_to_a_file              )              }              ,              // elements without holding `filename` will be sent as plain text              {              proper noun              :              'name'              ,              information              :              'user'              }              ,              {              name              :              'info'              ,              data              :              JSON              .              stringify              (              {              mail              :              'example@example.com'              ,              tel              :              '12345678'              }              )              }              ,              ]              )              .              then              (              (              resp              )              =>              {              // ...              }              )              .              grab              (              (              err              )              =>              {              // ...              }              )            

What if yous desire to append a file to class data? Just like upload a file from storage case, wrap information by wrap API (this feature is simply available for version >= v0.5.0). On version >= 0.six.2, information technology is possible to set custom MIME type when appending a file to form data. Simply keep in heed when the file is big information technology's probable to crash your app. Please consider use other strategy (come across #94).

              RNFetchBlob              .              fetch              (              'Post'              ,              'http://www.instance.com/upload-grade'              ,              {              Potency              :              "Bearer admission-token"              ,              otherHeader              :              "foo"              ,              // this is required, otherwise information technology won't be process as a multipart/course-data asking              'Content-Type'              :              'multipart/form-data'              ,              }              ,              [              // suspend field data from file path              {              name              :              'avatar'              ,              filename              :              'avatar.png'              ,              // Alter BASE64 encoded data to a file path with prefix `RNFetchBlob-file://`.              // Or simply wrap the file path with RNFetchBlob.wrap().              data:              RNFetchBlob              .              wrap              (              PATH_TO_THE_FILE              )              }              ,              {              name              :              'ringtone'              ,              filename              :              'ring.mp3'              ,              // use custom MIME type              blazon              :              'application/mp3'              ,              // upload a file from nugget is too possible in version >= 0.6.two              data              :              RNFetchBlob              .              wrap              (              RNFetchBlob              .              fs              .              asset              (              'default-ringtone.mp3'              )              )              }              // elements without property `filename` will be sent as plain text              {              name              :              'proper noun'              ,              data              :              'user'              }              ,              {              name              :              'info'              ,              data              :              JSON              .              stringify              (              {              mail              :              'example@instance.com'              ,              tel              :              '12345678'              }              )              }              ,              ]              )              .              and then              (              (              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 also supported.

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

In 0.ix.6, yous can specify an object equally the kickoff argument which contains count and interval, to the frequency of progress result (this will be done in the native context a reduce RCT bridge overhead). Notice that count argument will non work if the server does not provide response content length.

              RNFetchBlob              .              fetch              (              'POST'              ,              'http://www.example.com/upload'              ,              {              //... some headers,              'Content-Type'              :              'octet-stream'              }              ,              base64DataString              )              // heed to upload progress event, emit every 250ms              .              uploadProgress              (              {              interval              :              250              }              ,              (              written              ,              full              )              =>              {              console              .              log              (              'uploaded'              ,              written              /              total              )              }              )              // listen to download progress issue, every 10%              .              progress              (              {              count              :              10              }              ,              (              received              ,              total              )              =>              {              console              .              log              (              'progress'              ,              received              /              total              )              }              )              .              then              (              (              resp              )              =>              {              // ...              }              )              .              catch              (              (              err              )              =>              {              // ...              }              )            

Cancel Asking

After 0.7.0 it is possible to cancel an HTTP request. Upon counterfoil, information technology throws a hope rejection, be sure to grab information technology.

              allow              task              =              RNFetchBlob              .              fetch              (              'Get'              ,              'http://example.com/file/1'              )              chore              .              so              (              (              )              =>              {              ...              }              )              // handle request cancelled rejection              .              catch              (              (              err              )              =>              {              panel              .              log              (              err              )              }              )              // abolish the request, the callback office is optional              job              .              abolish              (              (              err              )              =>              {              ...              }              )            

Drop-in Fetch Replacement

0.nine.0

If you take existing code that uses whatwg-fetch(the official fetch), it's not necessary to replace them with RNFetchblob.fetch, you tin simply use our Fetch Replacement. The difference betwixt Official them is official fetch uses whatwg-fetch which wraps XMLHttpRequest polyfill under the hood. It's a corking library for spider web developers, but does not play very well with RN. Our implementation is simply a wrapper of our fetch and fs APIs, so you tin can access all the features we provided.

See document and examples

Android Media Scanner, and Download Manager Support

If you want to make a file in External Storage becomes visible in Picture, Downloads, or other built-in apps, you lot volition have to employ Media Scanner or Download Manager.

Media Scanner

Media scanner scans the file and categorizes by given MIME type, if MIME type not specified, information technology 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://case.com/music.mp3'              )              .              and so              (              (              res              )              =>              RNFetchBlob              .              fs              .              scanFile              (              [              {              path              :              res              .              path              (              )              ,              mime              :              'sound/mpeg'              }              ]              )              )              .              then              (              (              )              =>              {              // scan file success              }              )              .              catch              (              (              err              )              =>              {              // scan file error              }              )            

Download Manager

When downloading large files on Android it is recommended to use Download Manager, it supports a lot of native features similar the progress bar, and notification, as well the download task volition be handled by OS, and more than efficient.

When using DownloadManager, fileCache and path properties in config will non take event, because Android DownloadManager tin just store files to external storage, likewise find that Download Manager can merely back up Get method, which means the request torso will be ignored.

When download consummate, DownloadManager will generate a file path so that yous can deal with information technology.

              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, past default the mime type volition be text/plain              mime              :              'text/plain'              ,              description              :              'File downloaded past download director.'              }              }              )              .              fetch              (              'GET'              ,              'http://example.com/file/somefile'              )              .              so              (              (              resp              )              =>              {              // the path of downloaded file              resp              .              path              (              )              }              )            

Your app might not take correct to remove/change the file created by Download Manager, therefore you might demand to gear up custom location to the download job.

Download Notification and Visibility in Download App (Android Only)

If you need to display a notification upon the file is downloaded to storage (as the above) or make the downloaded file visible in "Downloads" app. Y'all have to add some options to config.

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

Open Downloaded File with Intent

This is a new feature added in 0.ix.0 if you're going to open up a file path using official Linking API that might non piece of work as expected, also, if you lot're going to install an APK in Downloads app, that will not function too. Every bit an culling, you tin try actionViewIntent API, which will transport an ACTION_VIEW intent for you which uses the given MIME type.

Download and install an APK programmatically

              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://world wide web.example.com/awesome.apk`              )              .              and then              (              (              res              )              =>              {              android              .              actionViewIntent              (              res              .              path              (              )              ,              'application/vnd.android.parcel-archive'              )              }              )            

Or show an image in image viewer

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

File System

File Admission

File access APIs were fabricated when developing v0.5.0, which helping us write tests, and was non planned to exist a office of this module. However, we realized that information technology's hard to notice a peachy solution to manage buried files, everyone who uses this module may need these APIs for their cases.

Before start using file APIs, we recommend read Differences between File Source first.

File Access APIs

  • nugget (0.half dozen.two)
  • dirs
  • createFile
  • writeFile (0.6.0)
  • appendFile (0.vi.0)
  • readFile (0.6.0)
  • readStream
  • hash (0.x.9)
  • writeStream
  • hash
  • unlink
  • mkdir
  • ls
  • mv
  • cp
  • exists
  • isDir
  • stat
  • lstat
  • scanFile (Android just)

See File API for more information

File Stream

In v0.5.0 nosotros've added writeStream and readStream, which allows your app read/write information from the file path. This API creates a file stream, rather than catechumen unabridged 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 advisable bufferSize and interval to reduce the native issue dispatching overhead (run across Performance Tips)

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

              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 be multiples of three.              4095              )              .              and so              (              (              ifstream              )              =>              {              ifstream              .              open              (              )              ifstream              .              onData              (              (              chunk              )              =>              {              // when encoding is `ascii`, chunk volition exist an array contains numbers              // otherwise it will be a string              data              +=              chunk              }              )              ifstream              .              onError              (              (              err              )              =>              {              panel              .              log              (              'oops'              ,              err              )              }              )              ifstream              .              onEnd              (              (              )              =>              {              <              Image              source              =              {              {              uri              :              'data:image/png,base64'              +              data              }              }              }              )              }              )            

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

Since version 0.x.9 write() resolves with the RNFetchBlob instance so yous tin can promise-chain write calls:

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

or

              RNFetchBlob              .              fs              .              writeStream              (              PATH_TO_FILE              ,              // encoding, should exist one of `base64`, `utf8`, `ascii`              'utf8'              ,              // should information append to existing content ?              true              )              .              then              (              stream              =>              Hope              .              all              (              [              stream              .              write              (              'foo'              )              ,              stream              .              write              (              'bar'              )              ,              stream              .              write              (              'foobar'              )              ]              )              )              // Employ array destructuring to get the stream object from the first item of the array nosotros get from Promise.all()              .              then              (              (              [              stream              ]              )              =>              stream              .              close              (              )              )              .              catch              (              console              .              error              )            

You lot should NOT do something like this:

              RNFetchBlob              .              fs              .              writeStream              (              PATH_TO_FILE              ,              // encoding, should exist one of `base64`, `utf8`, `ascii`              'utf8'              ,              // should information append to existing content ?              true              )              .              then              (              (              ofstream              )              =>              {              // BAD IDEA - Don't do this, those writes are unchecked:              ofstream              .              write              (              'foo'              )              ofstream              .              write              (              'bar'              )              ofstream              .              close              (              )              }              )              .              grab              (              panel              .              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 means the entire hope chain A) resolves without waiting for the writes to stop and B) any errors caused past them are lost. That lawmaking may seem to work if in that location are no errors, but those writes are of the type "fire and forget": Y'all first them and so turn abroad and never know if they really succeeded.

Cache File Direction

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              :              true              }              )              .              fetch              (              'GET'              ,              'http://example.com/download/file'              )              .              then              (              (              res              )              =>              {              // remove cached file from storage              res              .              affluent              (              )              }              )              // remove file past specifying a path              RNFetchBlob              .              fs              .              unlink              (              'some-file-path'              )              .              then              (              (              )              =>              {              // ...              }              )            

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

              RNFetchblob              .              config              (              {              fileCache              :              true              }              )              .              fetch              (              'GET'              ,              'http://example.com/download/file'              )              .              then              (              (              res              )              =>              {              // set session of a response              res              .              session              (              'foo'              )              }              )              RNFetchblob              .              config              (              {              // you can likewise set session beforehand              session              :              'foo'              fileCache              :              true              }              )              .              fetch              (              'GET'              ,              'http://example.com/download/file'              )              .              so              (              (              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

After 0.9.four, the Chunked transfer encoding is disabled by default due to some service provider may non support chunked transfer. To enable it, fix Transfer-Encoding header to Chunked.

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

Self-Signed SSL Server

By default, rn-fetch-blob does Not permit connection to unknown certification provider since it's unsafe. To connect a server with self-signed certification, you demand to add trusty to config explicitly. This function is bachelor for version >= 0.5.iii

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

WiFi only requests

If y'all wish to merely route requests through the Wifi interface, set the beneath configuration. Notation: On Android, the ACCESS_NETWORK_STATE permission must be set, and this flag volition simply piece of work on API version 21 (Lollipop, Android 5.0) or to a higher place. APIs below 21 will ignore this flag.

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

Web API Polyfills

Later on 0.8.0 we've made some Web API polyfills that makes some browser-based library available in RN.

  • Hulk
  • XMLHttpRequest (Use our implementation if you're going to utilise it 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 large when reading information via fs.readStream. Information technology might because the default buffer size is quite pocket-sized (4kb) which effect in a lot of events triggered from JS thread. Try to increase the buffer size (for instance 100kb = 102400) and set up a larger interval (bachelor for 0.9.four+, the default value is 10ms) to limit the frequency.

Reduce RCT Bridge and BASE64 Overhead

React Native connects JS and Native context past passing JSON around React Native bridge, and there will be an overhead to convert data before they sent to each side. When information is large, this will be quite a performance bear upon to your app. It'southward recommended to utilise file storage instead of BASE64 if possible.The following chart shows how much faster when loading information from storage than BASE64 encoded string on iPhone half-dozen.

ASCII Encoding has /terrible Performance

Due to the lack of typed array implementation in JavascriptCore, and limitation of React Native structure, to catechumen information to JS byte assortment spends lot of time. Employ it only when needed, the post-obit chart shows how much fourth dimension it takes when reading a file with different encoding.

Concat and Replacing Files

If yous're going to concatenate files, you don't accept to read the data to JS context anymore! In 0.viii.0 nosotros introduced new encoding uri for writeFile and appendFile API, which make it possible to handle the whole process in native.

Caveats

  • This library does non urlencode unicode characters in URL automatically, meet #146.
  • When you create a Hulk , from an existing file, the file Volition Be REMOVED if you lot close the blob.
  • If you lot replaced window.XMLHttpRequest for some reason (e.g. make Firebase SDK piece of work), information technology will also affect how official fetch works (basically information technology should work just fine).
  • When file stream and upload/download progress outcome slow down your app, consider an upgrade to 0.9.half dozen+, use additional arguments to limit its frequency.
  • When passing a file path to the library, remove file:// prefix.

when you got a trouble, have a look at Problem Shooting or issues labeled Problem Shooting, there'd exist some helpful information.

Changes

Meet release notes

Development

If yous're interested in hacking this module, check our development guide, there might be some helpful information. Delight experience free to make a PR or file an result.

bellwillet.blogspot.com

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

0 Response to "Upload Image as Byte Array of Hash"

ارسال یک نظر

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel