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
cryptoModuleduring initialization. In Node.js and in browsers,sendFile()encrypts the file content with it. React Native does not encrypt file content. WithcryptoModuleconfigured, the SDK also encrypts the file message, which holdsmessage, the file ID, and the file name. The SDK sendschannelandmetaunencrypted.
channelrequired#- 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. filerequired#- File to upload. The accepted forms depend on the environment.
message#- Message that travels with the file, such as a caption. Subscribers receive it in the file event. The SDK omits a falsy value.
storeInHistory#- Whether PubNub stores the file message in Message Persistence.
truestores it andfalseskips storage. PubNub stores the message only when Message Persistence is enabled for the keyset. When omitted, the SDK sendstrue, so the Message Persistence setting of the keyset does not decide. ttl#- 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#- Metadata that PubNub attaches to the file message. Subscribers can use it in message filters. The SDK sends
metaonly when it is an object or an array. customMessageType#- A business-specific label for the message, for example
text,action, orpoll.
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.
Sample code
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.
Other examples
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 linesFor 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.
| Condition | Result |
|---|---|
The SDK cannot build the file from file | A 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 empty | PNValidationErrorCategory. The status.message value is channel can't be empty. |
The upload to the storage service does not return HTTP 204 | A 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 attempt | A 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(). |
Examples for Send file
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>;
Basic usage
1
1
Returns
1type SendFileResponse = {
2 status: number,
3 timetoken: string,
4 id: string,
5 name: string
6}
List channel files
listFiles() returns the files that File Sharing stores for a channel, using a PubNub client for JavaScript.
channelrequired#- 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#- Number of files to return in one call. A single list-files call returns up to 100 files for a channel.
next#- Token from the
nextvalue of the previous response, which continues the list where that response ended.
Sample code
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.
Examples for List channel files
Syntax
1pubnub.listFiles({
2 channel: string,
3 limit?: number,
4 next?: string
5}): Promise<ListFilesResponse>;
Basic usage
1
Returns
1type ListFilesResponse = {
2 status: number,
3 data: Array<{
4 name: string,
5 id: string,
6 size: number,
7 created: string
8 }>,
9 next: string,
10 count: number
11}
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.
channelrequired#- ID of the channel that holds the file. The method takes the ID string, not an SDK channel entity.
idrequired#- ID of the file to build the URL for, which PubNub assigned at upload.
namerequired#- Name of the file to build the URL for, as PubNub stores it.
Sample code
Returns
getFileUrl() returns the download URL as a string. The auth parameter appears only when the client has an authentication key or token.
Examples for Get file URL
Syntax
1pubnub.getFileUrl({
2 channel: string,
3 id: string,
4 name: string
5}): string;
Basic usage
1
Returns
1'https://ps.pndsn.com/v1/files/demo/channels/my_channel/files/12345678-1234-5678-123456789012/cat_picture.jpg?pnsdk=PubNub-JS-Web%2F13.1.2&uuid=myUniqueUserId'
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.
channelrequired#- 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. idrequired#- ID of the file to download, which PubNub assigned at upload. The SDK rejects an empty value with
file id can't be empty. namerequired#- 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.
Sample code
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.
Examples for Download file
Syntax
1pubnub.downloadFile({
2 channel: string,
3 id: string,
4 name: string
5}): Promise<PubNubFile>;
Basic usage (Node.js)
1
Basic usage (Browser)
1
Basic usage (React and React Native)
1
Delete file
deleteFile() deletes a file from a channel through a PubNub client for JavaScript.
channelrequired#- 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. idrequired#- ID of the file to delete, which PubNub assigned at upload. The SDK rejects an empty value with
file id can't be empty. namerequired#- Name of the file to delete, as PubNub stores it. The SDK rejects an empty value with
file name can't be empty.
Sample code
Returns
deleteFile() resolves with a DeleteFileResponse. A successful deletion returns the status 200.
Examples for Delete file
Syntax
1pubnub.deleteFile({
2 channel: string,
3 id: string,
4 name: string
5}): Promise<DeleteFileResponse>;
Basic usage
1
Returns
1type DeleteFileResponse = {
2 status: number
3}
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.
channelrequired#- 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. fileIdrequired#- ID of the uploaded file, which PubNub assigned at upload. The SDK rejects an empty value with
file id can't be empty. fileNamerequired#- Name of the uploaded file, as PubNub stores it. The SDK rejects an empty value with
file name can't be empty. message#- Message to publish with the file. Subscribers receive it in the file event. The SDK omits a falsy value.
storeInHistory#- Whether PubNub stores the file message in Message Persistence.
truestores it andfalseskips storage. PubNub stores the message only when Message Persistence is enabled for the keyset. When omitted, the SDK sendstrue, so the Message Persistence setting of the keyset does not decide. ttl#- 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#- Metadata that PubNub attaches to the file message. Subscribers can use it in message filters. The SDK sends
metaonly when it is an object or an array.
Sample code
Returns
publishFile() resolves with a PublishFileMessageResponse. The timetoken is a string.
Examples for Publish file message
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>;
Basic usage
1
Returns
1type PublishFileMessageResponse = {
2 timetoken: string
3}
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.
Examples for FileInput
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.