File Sharing API for JavaScript SDK

The PubNub JavaScript SDK uploads, lists, downloads, and deletes files on channels with File Sharing, and sendFile() publishes a file message that announces each upload.

File Sharing must be enabled for the keyset in the Admin Portal. A file can be up to 5 MB. When Access Manager (v2/v3) is enabled, file operations need channel permissions. For how File Sharing works, retention, and permissions, see Files.

Each method except getFileUrl() returns a promise that resolves with the response and rejects with a PubNubError. The error carries a status object with category and statusCode, and status.errorData holds the details that PubNub returned for a failed request. Each method except getFileUrl() also takes a callback as the second argument, and with a callback the method returns nothing and PubNub calls it with (status, response). On success, status.error is false and status.operation names the operation, and on failure status.error is true and response is null. All examples use async/await, so wrap a call in try...catch to receive the error status.

sendFile() is the exception on failure: it calls the callback and also rejects its promise.

The methods take channel ID strings, not SDK channel entities.

Send file​

sendFile() uploads a file to a channel through a PubNub client for JavaScript, then publishes a file message that announces the upload.

sendFile() requests an upload URL from PubNub, uploads the file to the storage service, and publishes the file message with the file ID and name. For the publish step, see Publish file message.

  • Subscribers to the channel receive a file event with the file ID, the file name, and the optional message that came with the upload.
  • To encrypt files, configure a cryptoModule during initialization. In Node.js and in browsers, sendFile() encrypts the file content with it. React Native does not encrypt file content. With cryptoModule configured, the SDK also encrypts the file message, which holds message, the file ID, and the file name. The SDK sends channel and meta unencrypted.
required
channel required#
Type: string
Default: no default
ID of the channel to upload the file to. The method takes the ID string, not an SDK channel entity. The SDK rejects an empty value with channel can't be empty.
file required#
Type: FileInput
Default: no default
File to upload. The accepted forms depend on the environment.
message#
Type: any
Default: no default
Message that travels with the file, such as a caption. Subscribers receive it in the file event. The SDK omits a falsy value.
storeInHistory#
Type: boolean
Default: true
Whether PubNub stores the file message in Message Persistence. true stores it and false skips storage. PubNub stores the message only when Message Persistence is enabled for the keyset. When omitted, the SDK sends true, so the Message Persistence setting of the keyset does not decide.
ttl#
Type: number
Default: no default
The number of hours that Message Persistence keeps the file message. When omitted, the retention of the keyset applies. PubNub ignores this value when it does not store the message. The SDK omits the value 0, so the retention of the keyset applies.
meta#
Type: any
Default: no default
Metadata that PubNub attaches to the file message. Subscribers can use it in message filters. The SDK sends meta only when it is an object or an array.
customMessageType#
Type: string
Default: no default
A business-specific label for the message, for example text, action, or poll.

A custom message type accepted by the PubNub Publish, Signal, and File Sharing APIs must be a case-sensitive alphanumeric string of 3 to 50 characters. Dashes (-) and underscores (_) are allowed. The value cannot start with a special character or with the reserved prefixes pn_ or pn-.

The deprecated cipherKey parameter is documented in Deprecated cipherKey parameter.

Returns​

sendFile() resolves with a SendFileResponse. The timetoken is a string. The id and name identify the file that PubNub stores, and name is the name under which PubNub stores it.

Send file with push notification​

Trigger push notifications when sharing files

To send mobile push notifications when sharing a file, include pn_apns (for iOS) and/or pn_fcm (for Android) payloads in the message parameter of the sendFile method.

When PubNub detects these reserved keys, it automatically forwards the push notification to the appropriate push service (APNs or FCM) for all devices registered on the channel.

1// Create a notification payload with title and body
2const notificationPayload = PubNub.notificationPayload('New File', 'A file was shared');
3
4// Configure APNS2 with your specific topic and environment
5notificationPayload.apns.configurations = [
6{
7 targets: [
8 {
9 topic: 'com.yourapp.bundleid',
10 environment: 'production',
11 },
12 ],
13},
14];
15
show all 28 lines

For more details on push notification payload structure, see the iOS Push and Android Push documentation. To prevent the sender from receiving their own push notification, add their device token to excluded_devices in the pn_push targets.

Send file errors​

sendFile() rejects with a PubNubError, except when the SDK cannot build the file from file. Read error.status.category and error.status.statusCode to tell the cases apart.

ConditionResult
The SDK cannot build the file from fileA plain Error with the message Couldn't construct a file out of supplied options. or Couldn't guess filename out of the options. Please provide one., and no callback call.
channel is emptyPNValidationErrorCategory. The status.message value is channel can't be empty.
The upload to the storage service does not return HTTP 204A PubNubError whose status.statusCode is the HTTP status of the upload. The status.errorData.message value holds the reply of the storage service.
The publish step fails on every attemptA PubNubError whose status holds the channel, id, and name of the uploaded file. By default, the SDK makes 5 attempts. Pass the three values to publishFile().

Syntax

1pubnub.sendFile({
2 channel: string,
3 file: FileInput,
4 message?: any,
5 storeInHistory?: boolean,
6 ttl?: number,
7 meta?: any,
8 customMessageType?: string
9}): Promise<SendFileResponse>;

List channel files​

listFiles() returns the files that File Sharing stores for a channel, using a PubNub client for JavaScript.

required
channel required#
Type: string
Default: no default
ID of the channel to list the files of. The method takes the ID string, not an SDK channel entity. The SDK rejects an empty value with channel can't be empty.
limit#
Type: number
Default: 100
Number of files to return in one call. A single list-files call returns up to 100 files for a channel.
next#
Type: string
Default: no default
Token from the next value of the previous response, which continues the list where that response ended.

Returns​

listFiles() resolves with a ListFilesResponse. The data array holds one entry per file, and created is an ISO 8601 time string. The count value is the number of files in the response, and next is the token for the next page.

Syntax

1pubnub.listFiles({
2 channel: string,
3 limit?: number,
4 next?: string
5}): Promise<ListFilesResponse>;

Get file URL​

getFileUrl() builds the download URL of a file on a channel for a PubNub client for JavaScript, and sends no request to PubNub.

getFileUrl() returns the URL as a string and takes no callback. The method does not validate its parameters. The URL points to the file as PubNub stores it, so a file that the sender encrypted stays encrypted. The URL carries the query parameters that the SDK adds to every request, such as pnsdk, uuid, and auth.

required
channel required#
Type: string
Default: no default
ID of the channel that holds the file. The method takes the ID string, not an SDK channel entity.
id required#
Type: string
Default: no default
ID of the file to build the URL for, which PubNub assigned at upload.
name required#
Type: string
Default: no default
Name of the file to build the URL for, as PubNub stores it.

Returns​

getFileUrl() returns the download URL as a string. The auth parameter appears only when the client has an authentication key or token.

Syntax

1pubnub.getFileUrl({
2 channel: string,
3 id: string,
4 name: string
5}): string;

Download file​

downloadFile() downloads a file from a channel through a PubNub client for JavaScript.

downloadFile() resolves with a PubNubFile instance. Convert it with the methods of PubNub file for your environment. With a cryptoModule configured, the SDK decrypts the file content in Node.js and in browsers. React Native does not decrypt file content.

required
channel required#
Type: string
Default: no default
ID of the channel to download the file from. The method takes the ID string, not an SDK channel entity. The SDK rejects an empty value with channel can't be empty.
id required#
Type: string
Default: no default
ID of the file to download, which PubNub assigned at upload. The SDK rejects an empty value with file id can't be empty.
name required#
Type: string
Default: no default
Name of the file to download, as PubNub stores it. The SDK rejects an empty value with file name can't be empty.

The deprecated cipherKey parameter is documented in Deprecated cipherKey parameter.

Choose the sample for your environment.

Returns​

downloadFile() resolves with a PubNubFile. In React Native, the file reads its content from an ArrayBuffer, so toBlob() and toFile() reject. Use toArrayBuffer() or toString() there.

Syntax

1pubnub.downloadFile({
2 channel: string,
3 id: string,
4 name: string
5}): Promise<PubNubFile>;

Delete file​

deleteFile() deletes a file from a channel through a PubNub client for JavaScript.

required
channel required#
Type: string
Default: no default
ID of the channel to delete the file from. The method takes the ID string, not an SDK channel entity. The SDK rejects an empty value with channel can't be empty.
id required#
Type: string
Default: no default
ID of the file to delete, which PubNub assigned at upload. The SDK rejects an empty value with file id can't be empty.
name required#
Type: string
Default: no default
Name of the file to delete, as PubNub stores it. The SDK rejects an empty value with file name can't be empty.

Returns​

deleteFile() resolves with a DeleteFileResponse. A successful deletion returns the status 200.

Syntax

1pubnub.deleteFile({
2 channel: string,
3 id: string,
4 name: string
5}): Promise<DeleteFileResponse>;

Publish file message​

publishFile() publishes a file message for a file that PubNub already stores, using a PubNub client for JavaScript.

The file message carries the file ID and the file name, which together identify the file for download. Call publishFile() when the upload succeeded but the publish step of sendFile() failed, to publish the file message without uploading the file again. When sendFile() rejects because the publish step failed, read channel, id, and name from error.status and pass them as channel, fileId, and fileName.

required
channel required#
Type: string
Default: no default
ID of the channel to publish the file message to. The method takes the ID string, not an SDK channel entity. The SDK rejects an empty value with channel can't be empty.
fileId required#
Type: string
Default: no default
ID of the uploaded file, which PubNub assigned at upload. The SDK rejects an empty value with file id can't be empty.
fileName required#
Type: string
Default: no default
Name of the uploaded file, as PubNub stores it. The SDK rejects an empty value with file name can't be empty.
message#
Type: any
Default: no default
Message to publish with the file. Subscribers receive it in the file event. The SDK omits a falsy value.
storeInHistory#
Type: boolean
Default: true
Whether PubNub stores the file message in Message Persistence. true stores it and false skips storage. PubNub stores the message only when Message Persistence is enabled for the keyset. When omitted, the SDK sends true, so the Message Persistence setting of the keyset does not decide.
ttl#
Type: number
Default: no default
The number of hours that Message Persistence keeps the file message. When omitted, the retention of the keyset applies. PubNub ignores this value when it does not store the message. The SDK omits the value 0, so the retention of the keyset applies.
meta#
Type: any
Default: no default
Metadata that PubNub attaches to the file message. Subscribers can use it in message filters. The SDK sends meta only when it is an object or an array.
customMessageType#
Type: string
Default: no default
A business-specific label for the file message, for example text, action, or poll. The accepted format is the same as for sendFile(). See Send file.

Returns​

publishFile() resolves with a PublishFileMessageResponse. The timetoken is a string.

Syntax

1pubnub.publishFile({
2 channel: string,
3 fileId: string,
4 fileName: string,
5 message?: any,
6 storeInHistory?: boolean,
7 ttl?: number,
8 meta?: any,
9 customMessageType?: string
10}): Promise<PublishFileMessageResponse>;

FileInput​

FileInput describes the values that the file parameter of sendFile() accepts in the PubNub JavaScript SDK. The accepted forms depend on the environment.

Node.js​

In Node.js, mimeType defaults to application/octet-stream. The data property accepts a Buffer, an ArrayBuffer, or a string. For a string, the optional encoding property sets the encoding and defaults to utf8.

Browsers​

In a browser, file accepts a File or an object whose data property is a string, an ArrayBuffer, an ArrayBufferView, or a Blob.

The data property also accepts a Blob or an ArrayBufferView.

React and React Native​

React in a browser accepts the forms of the browser. React Native accepts a File, an object with a data property like the one for browsers, and an object with a uri property.

Using streams

Using streams​

1{
2 stream: Readable,
3 name: string,
4 mimeType?: string
5}

PubNub file​

PubNubFile is the file object of the PubNub JavaScript SDK. downloadFile() resolves with it, and sendFile() builds it from FileInput. The methods that work depend on the environment, and a method that the environment does not support rejects.

Methods supported in Node.js​

In Node.js, file.toBuffer() resolves with a Buffer, file.toStream() resolves with a Readable stream, and file.toArrayBuffer() resolves with an ArrayBuffer. The method file.toString(encoding?: string) resolves with a string encoded with encoding, which defaults to utf8. The methods toFile(), toBlob(), and toFileUri() reject.

Methods supported in a browser​

In a browser, file.toFile() resolves with a File, file.toBlob() resolves with a Blob, and file.toArrayBuffer() resolves with an ArrayBuffer. The method file.toString() resolves with a string that holds the binary content of the file and takes no encoding argument. The methods toBuffer(), toStream(), and toFileUri() reject.

Methods supported in React Native​

In React Native, file.toArrayBuffer() resolves with an ArrayBuffer, and file.toString() resolves with a string and takes no encoding argument. For a file that you created from a File, file.toBlob() and file.toFile() resolve with that File. For a file that you created from a string or a Blob, they resolve with a Blob. Both reject for a file that you created from an ArrayBuffer, a typed array, or a uri, and for a file that downloadFile() returns, so use toArrayBuffer() there.

In React Native, file.toFileUri() resolves with the { uri, name, type } object of a file that you created from a uri and rejects for any other file. The methods toBuffer() and toStream() reject.

Deprecated cipherKey parameter​

The cipherKey parameter of sendFile() and downloadFile() still works in the PubNub JavaScript SDK, and a crypto module replaces it.

The reference for apps that still pass cipherKey, with the replacement, is File Sharing API: deprecated cipherKey parameter for JavaScript SDK. New apps configure a cryptoModule.

Was this page useful?

Last updated on