5.0.2 • Published 15 days ago

react-native-blob-courier v5.0.2

Weekly downloads
66
License
MPL-2.0
Repository
github
Last release
15 days ago

react-native-blob-courier

License: MPL 2.0 Build

Use this library to efficiently download and upload data in React Native. The library was inspired by rn-fetch-blob, and is focused strictly on http file transfers.

Installation

Install using yarn

yarn add react-native-blob-courier

Or install using npm

npm install react-native-blob-courier

Requirements

  • Android >= 24
  • Android Gradle Plugin >= 7.5.1
  • iOS >= 13.0
  • JDK >= 11
  • React Native >= 0.69.x

Note: you may have success with earlier versions of React Native but these are neither tested nor supported.

Usage

The library provides both a fluent and a more concise interface. In the examples the concise approach is applied; fluent interface is demonstrated later in this document.

Straightforward down- and upload

import BlobCourier from 'react-native-blob-courier';

// ...

// Download a file
const request0 = {
  filename: '5MB.zip',
  method: 'GET',
  mimeType: 'application/zip',
  url: 'http://ipv4.download.thinkbroadband.com/5MB.zip',
};

const fetchedResult = await BlobCourier.fetchBlob(request0);
console.log(fetchedResult);
// {
//   "data": {
//     "absoluteFilePath": "/path/to/app/cache/5MB.zip",
//     "response": {
//       "code":200,
//       "headers": {
//         "some_header": "some_value",
//         ...
//       }
//     },
//   },
//   "type":"Unmanaged"
// }

// ...

// Upload a file
const absoluteFilePath = fetchedResult.data.absoluteFilePath;

const request1 = {
  absoluteFilePath,
  method: 'POST',
  mimeType: 'application/zip',
  url: 'https://file.io',
};

const uploadResult = await BlobCourier.uploadBlob(request1);

console.log(uploadResult):
// {
//   "response": {
//     "code": {
//     "data": "<some response>",
//     "headers": {
//       "some_header": "some_value",
//        ...
//      }
//   }
// }

// Multipart file upload
const absoluteFilePath = fetchedResult.data.absoluteFilePath;

const request2 = {
  method: 'POST',
  parts: {
    body: {
      payload: 'some_value',
      type: 'string',
    },
    file: {
      payload: {
        absoluteFilePath,
        mimeType: 'application/zip',
      },
      type: 'file',
    },
  },
  url: 'https://file.io',
};

const multipartUploadResult = await BlobCourier.uploadBlob(request1);

console.log(multipartUploadResult):
// {
//   "response": {
//     "code": {
//     "data": "<some response>",
//     "headers": {
//       "some_header": "some_value",
//        ...
//      }
//   }
// }

Transfer progress reporting

import BlobCourier from 'react-native-blob-courier';

// ...

// Download a file
const request0 = {
  // ...
  onProgress: ((e: BlobProgressEvent) => {
    console.log(e)
    // {
    //  "written": <some_number_of_bytes_written>,
    //  "total": <some_total_number_of_bytes>
    // }
  })
};

const fetchedResult = await BlobCourier.fetchBlob(request0);

// ...

// Upload a file
const request1 = {
  // ...
  onProgress: ((e: BlobProgressEvent) => {
    console.log(e)
    // {
    //  "written": <some_number_of_bytes_written>,
    //  "total": <some_total_number_of_bytes>
    // }
  })
};

const uploadResult = await BlobCourier.uploadBlob(request1)

// ...

// Set progress updater interval
const request2 = ...

const someResult =
  await BlobCourier
    .fetchBlob({
      ...request2,
      progressIntervalMilliseconds: 1000,
    });

Managed download on Android (not available on iOS)

import BlobCourier from 'react-native-blob-courier';

// ...

const request = {
  android: {
    useDownloadManager: true // <--- set useDownloadManager to "true"
  },
  filename: '5MB.zip',
  method: 'GET',
  mimeType: 'application/zip',
  url: 'http://ipv4.download.thinkbroadband.com/5MB.zip',
};

const fetchResult = await BlobCourier.fetchBlob(request);

console.log(fetchedResult);
// {
//   "data": {
//     "result": "SUCCESS",
//     "absoluteFilePath": "/path/to/app/cache/5MB.zip"
//   },
//   "type":"Managed"
// }

Multipart upload

Sometimes order of multipart fields matters, and Blob Courier respects the order in which parts are provided. There is a catch though: due to how JavaScript works, when object keys are regular strings they are kept in the order they were added unless the keys are strings containing numbers, e.g.:

Object.keys({
  "b": "some_value1",
  "c": "some_value2",
  "a": "some_value3",
})

// ['b', 'c', 'a']

Object.keys({
  "b": "some_value1",
  "c": "some_value2",
  "a": "some_value3",
  "3": "some_value4",
  "2": "some_value5",
  "1": "some_value6",
});

// ['1', '2', '3', 'b', 'c', 'a']

The way to work around this, is to wrap all keys in a Symbol, by using Symbol.for. Do not use Symbol(<value>), this will not work, e.g.:

Object.getOwnPropertySymbols({
  [Symbol.for("b")]: "some_value1",
  [Symbol.for("c")]: "some_value2",
  [Symbol.for("a")]: "some_value3",
  [Symbol.for("3")]: "some_value4",
  [Symbol.for("2")]: "some_value5",
  [Symbol.for("1")]: "some_value6",
});

// [Symbol('b'), Symbol('c'), Symbol('a'), Symbol('3'), Symbol('2'), Symbol('1')]

Cancel request

import BlobCourier from 'react-native-blob-courier';

// ...

const abortController = new AbortController();

const { signal } = abortController;

const request0 = {
  // ...
  signal,
};

try {
  BlobCourier.fetchBlob(request0);

  abortController.abort();
} catch (e) {
  if (e.code === ERROR_CANCELED_EXCEPTION) {
    // ...
  }
}

// ...

Fluent interface

Blob Courier provides a fluent interface, that both protects you from using impossible setting combinations and arguably improves readability.

const req0 = ...

const someResult =
  await BlobCourier
    .settings({
      progressIntervalMilliseconds: 1000,
    })
    .onProgress((e: BlobProgressEvent) => {
      // ...
    })
    .useDownloadManagerOnAndroid({
      description: "Some file description",
      enableNotification: true,
      title: "Some title"
    })
    .fetchBlob(req0)

Available methods

fetchBlob(input: BlobFetchRequest)

Required

FieldTypeDescription
filenamestringThe name the file will have on disk after fetch.
mimeTypestringWhat is the mime type of the blob being transferred?
urlstringFrom which url will the blob be fetched?

Optional

FieldTypeDescriptionDefault
androidAndroidSettingsSettings to be used on Android{ downloadManager: {}, target: 'cache', useDownloadManager: false }
iosIOSSettingsSettings to be used on iOS{ target: 'cache' }
headers{ [key: string]: string }Map of headers to send with the request{}
methodstringRepresenting the HTTP methodGET
onProgress(e: BlobProgressEvent) => voidFunction handling progress updates() => { }
signalAbortSignalRequest cancellation managernull

Response

FieldTypeDescription
type"Managed" \| "Unmanaged"Was the blob downloaded through Android Download Manager, or without?
dataBlobManagedData \| BlobUnmanagedDataEither managed or HTTP response data

uploadBlob(input: BlobUploadRequest)

Alias for:

const someResult =
  await BlobCourier
   // ...
   .uploadParts({
     headers,
     method,
     parts: {
       file:
         payload: {
           absoluteFilePath,
           filename,
           mimeType,
         },
         type: 'file',
       },
     },
     returnResponse,
     url,
   })

Required

FieldTypeDescription
absoluteFilePathstringPath to the file to be uploaded
mimeTypestringMime type of the blob being transferred
urlstringUrl to upload the blob to

Optional

FieldTypeDescriptionDefault
filenamestringName of the file on disk<name part of 'absoluteFilePath'>
headers{ [key: string]: string }Map of headers to send with the request{}
methodstringThe HTTP method to be used in the request"POST"
multipartNamestringName for the file multipart"file"
onProgress(e: BlobProgressEvent) => voidFunction handling progress updates() => { }
returnResponsebooleanReturn the HTTP response body?false
signalAbortSignalRequest cancellation managernull

uploadParts(input: BlobMultipartUploadRequest)

Required

FieldTypeDescription
parts{ [key: string]: BlobMultipart }The parts to be sent
urlstringUrl to upload the blob to

Optional

FieldTypeDescriptionDefault
headers{ [key: string]: string }Map of headers to send with the request{}
methodstringThe HTTP method to be used in the request"POST"
onProgress(e: BlobProgressEvent) => voidFunction handling progress updates() => { }
returnResponsebooleanReturn the HTTP response body?false
signalAbortSignalRequest cancellation managernull

Response

FieldTypeDescription
responseBlobUnmanagedHttpResponseThe HTTP response

AndroidDownloadManagerSettings

FieldTypeDescription
description?stringDescription of the downloaded file
enableNotification?booleanDisplay notification when download completes
title?stringTitle to be displayed with the download

AndroidSettings

FieldTypeDescription
downloadManagerAndroidDownloadManagerSettingsSettings to be used on download manager
target"cache" \| "data"Where will the file be stored?
useDownloadManagerbooleanEnable download manager on Android?

BlobManagedData

FieldTypeDescription
absoluteFilePathstringThe absolute file path to where the file was stored
result"SUCCESS" \| "FAILURE"Was the request successful or did it fail?

BlobMultipart

Required

FieldTypeDescription
payloadBlobMultipartFormData \| BlobMultipartFormDataFileContains the payload of the part
type"string" \| "file"What is the type of the payload?

BlobMultipartFormData

Type of string | { [key:string] : any }

BlobMultipartFormDataFile

Required

FieldTypeDescription
absoluteFilePathstringPath to the file to be uploaded
mimeTypestringMime type of the blob being transferred

Optional

FieldTypeDescriptionDefault
filenamestringName of the file on disk<name part of 'absoluteFilePath'>

BlobProgressEvent

FieldTypeDescription
writtennumberNumber of bytes processed
totalnumberTotal number of bytes to be processed

BlobUnmanagedData

FieldTypeDescription
absoluteFilePathstringThe absolute file path to where the file was stored
responseBlobUnmanagedHttpResponseHTTP response, including headers and status code

BlobUnmanagedHttpResponse

FieldTypeDescription
codenumberHTTP status code
headers{ [key: string]: string }HTTP response headers

IOSSettings

FieldTypeDescription
target"cache" \| "data"Where will the file be stored?

Example app

You can find an example of how to use the library in the example directory.

Android

Permissions

Android 5.1 and below (API level < 23)

Add the following line to AndroidManifest.xml.

<manifest xmlns:android="http://schemas.android.com/apk/res/android" (...)>

+   <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" />
    (...)
    <application (...)>
      <activity (...)>
        <intent-filter>
          (...)
+          <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
        </intent-filter>
    (...)

Android 6.0+ (API level 23+)

Grant permissions using the PermissionAndroid API, like so:

const function App = () => {

  // ...

  React.useEffect(() => {
    const requestPermissionAsync = async () => {
      try {
        await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
        );

        // ...
      } catch (err) {
        console.error(err);
      }

      // ...
    };

    requestPermissionAsync();
  }, []);

  // ...

iOS

Add to Info.plist of your app:

<key>NSAllowsArbitraryLoads</key>
<true/>

Using the integrated download manager for Android

This library allows you to use the integrated download manager on Android, this option is not available for iOS.

To enable the download manager, simply set the request's useDownloadManager property of field android to true when passing it to fetchBlob, or call the useDownloadManagerOnAndroid method when using the fluent interface.

Shared directories

As this library is focused on transferring files, it only supports storage to the app's cache and data directories. To move files from these app specific directories to other locations on the filesystem, use another library like @react-native-community/cameraroll, e.g.:

import BlobCourier from 'react-native-blob-courier';
import CameraRoll from '@react-native-community/cameraroll';

// ...

const request = {
  filename: 'teh_cage640x360.png',
  method: 'GET',
  mimeType: 'image/png',
  url: 'https://www.placecage.com/640/360',
};

const cageResult = await BlobCourier.fetchBlob(request)

const cageLocalPath = cageResult.data.absoluteFilePath

CameraRoll.save(cageLocalPath);

Contributing

See the contributing guide to learn how to contribute to the repository and the development workflow.

Code of Conduct

Contributor Code of Conduct. By participating in this project you agree to abide by its terms.

License

MPL-2.0

5.0.2

15 days ago

5.0.1

15 days ago

5.0.0

2 months ago

4.0.0

1 year ago

3.1.1

1 year ago

3.0.12

2 years ago

3.1.0

2 years ago

3.0.10

2 years ago

3.0.11

2 years ago

3.0.8

2 years ago

3.0.9

2 years ago

3.0.7

2 years ago

3.0.6

2 years ago

3.0.5

2 years ago

3.0.4

2 years ago

3.0.3

2 years ago

3.0.2

2 years ago

3.0.1

2 years ago

3.0.0

2 years ago

2.0.6

3 years ago

2.0.5

3 years ago

2.0.4

3 years ago

2.0.3

3 years ago

1.1.2

3 years ago

2.0.2

3 years ago

2.0.1

3 years ago

2.0.0

3 years ago

1.1.1

3 years ago

1.1.0

3 years ago

1.0.12

3 years ago

1.0.11

3 years ago

1.0.10

3 years ago

1.0.9

3 years ago

1.0.8

3 years ago

1.0.7

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.1-beta.0

3 years ago

1.0.0

3 years ago

0.9.11

3 years ago

0.9.10

3 years ago

0.9.9

3 years ago

0.9.8

3 years ago

0.9.7

4 years ago

0.9.6

4 years ago

0.9.5

4 years ago

0.9.4

4 years ago

0.9.3

4 years ago

0.9.2

4 years ago

0.9.1

4 years ago

0.9.0

4 years ago