File Sharing API for PubNub JavaScript SDK

Allows users to upload and share files. You can upload any file of up to 5 MB in size. This feature is commonly used in social apps to share images, or in medical apps to share medical records for patients.

When a file is uploaded on a channel, it's stored and managed using a storage service, and associated with your key. Subscribers to that channel receive a file event which contains a file ID, filename, and optional description.

Supported and recommended asynchronous patterns

PubNub supports Callbacks, Promises, and Async/Await for asynchronous JS operations. The recommended pattern is Async/Await and all sample requests in this document are based on it. This pattern returns a status only on detecting an error. To receive the error status, you must add the try...catch syntax to your code.

Send file

Upload file / data to specified channel.

Method(s)

pubnub.sendFile(
params: SendFileParams
): Promise<SendFileResult>;
ParameterTypeRequiredDescription
paramsSendFileParamsYesParameters used to upload the file to a channel.

SendFileParams

ParameterTypeRequiredDefaultDescription
channelstringYesChannel to send the file to.
fileFileInputYesFile to send.
messageanyOptionalOptional message to attach to the file.
storeInHistorybooleanOptionaltrueWhether published file messages should be stored in the channel's history. If storeInHistory is not specified, then the history configuration on the key is used.
ttlnumberOptional0How long the message should be stored in the channel's history. If not specified, defaults to the key set's retention value.
metaanyOptionalMetadata for the message.
customMessageTypestringOptionalA case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn-.

Examples: text, action, poll.
Deprecated parameter

The cipherKey parameter in this method is deprecated. We recommend that you configure the crypto module on your PubNub instance instead.

If you pass cipherKey as an argument, it overrides the crypto module configuration and the legacy encryption with 128-bit cipher key entropy is used.

Basic Usage

// in browser
const input = document.querySelector('input[file]');

input.addEventListener('change', async () => {
const file = input.files[0];

const result = await pubnub.sendFile({
channel: 'my_channel',
file: file,
customMessageType: 'file-message',
});
});

// in Node.js
import fs from 'fs';
show all 37 lines

Returns

{
id: string,
name: string,
timetoken: string
}

Other Examples

Usage with a message and custom cipher key

// in Node.js
import fs from 'fs';

const myFile = fs.readFileSync('./cat_picture.jpg');

const result = await pubnub.sendFile({
channel: 'my_channel',
message: 'Look at this picture!',
file: { data: myFile, name: 'cat_picture.jpg', mimeType: 'application/json' },
cipherKey: 'myCipherKey',
});

List channel files

Retrieve list of files uploaded to Channel.

Method(s)

pubnub.listFiles(
params: ListFilesParams
): Promise<ListFilesResult>;
ParameterTypeRequiredDescription
paramsListFilesParamsYesParameters used to retrieve the list of uploaded files.

ListFilesParams

ParameterTypeRequiredDefaultDescription
channelstringYesRetrieve list of files for this channel.
limitnumberOptional100Number of files to return.
nextstringOptionalString token to get the next batch of files.

Basic Usage

const result = await pubnub.listFiles({ channel: 'my_channel' });

Returns

{
status: number,
data: Array<{
name: string,
id: string,
size: number,
created: string
}>,
next: string,
count: number,
}

Get File Url

Get a file's direct download URL. This method doesn't make any API calls, and won't decrypt an encrypted file.

Method(s)

pubnub.getFileUrl(
params: GetFileUrlParams
): string;
ParameterTypeRequiredDescription
paramsGetFileUrlParamsYesParameters used to construct file URL.

GetFileUrlParams

ParameterTypeRequiredDescription
channelstringYesChannel that the file was sent to.
idstringYesThe file's unique identifier.
namestringYesName of the file.

Basic Usage

const result = pubnub.getFileUrl({ channel: 'my_channel', id: '...', name: '...' });

Returns

'https://ps.pndsn.com/v1/files/demo/channels/my_channel/files/12345678-1234-5678-123456789012/cat_picture.jpg'

Download file

Download file from specified Channel.

Method(s)

pubnub.downloadFile(
params: DownloadFileParams
): Promise<DownloadFileResult>;
ParameterTypeRequiredDescription
paramsDownloadFileParamsYesParameters used to download the file.

DownloadFileParams

ParameterTypeRequiredDefaultDescription
channelstringYesChannel that the file was sent to.
idstringYesThe file's unique identifier.
namestringYesName of the file.
Deprecated parameter

The cipherKey parameter in this method is deprecated. We recommend that you configure the crypto module on your PubNub instance instead.

If you pass cipherKey as an argument, it overrides the crypto module configuration and the legacy encryption with 128-bit cipher key entropy is used.

Basic Usage

// In browser
const file = await pubnub.downloadFile({
channel: 'my_channel',
id: '...',
name: 'cat_picture.jpg',
});

const myImageTag = document.createElement('img');
myImageTag.src = URL.createObjectURL(await file.toFile());

document.body.appendChild(myImageTag);

// In Node.js using streams:
import fs from 'fs'

show all 38 lines

Returns

Returns instance of PubNubFile.

Other Examples

Usage with custom cipher key

const file = await pubnub.downloadFile({
channel: "my_channel",
id: "...",
name: "cat_picture.jpg",
cipherKey: "myCipherKey",
});

Delete file

Delete file from specified Channel.

Method(s)

pubnub.deleteFile(
params: DeleteFileParams
): Promise<DeleteFileResult>;
ParameterTypeRequiredDescription
paramsDeleteFileParamsYesParameters used to delete the file.

DeleteFileParams

ParameterTypeRequiredDescription
channelstringYesChannel that the file was sent to.
idstringYesThe file's unique identifier.
namestringYesName of the file.

Basic Usage

const result = await pubnub.deleteFile({
channel: "my_channel",
id: "...",
name: "cat_picture.jpg",
});

Returns

Example of successful deletion:

{
status: 200
}

Publish file message

Publish file message from specified Channel.

Method(s)

pubnub.publishFile(
params: PublishFileParams
): Promise<PublishFileResult>;
ParameterTypeRequiredDescription
paramsPublishFileParamsYesParameters used to publish the file.

PublishFileParams

ParameterTypeRequiredDefaultDescription
channelstringYesChannel to which the file was sent.
messageanyOptionalOptional message to attach to the file.
fileIdstringYesThe file's unique identifier.
fileNamestringYesName of the file.
storeInHistorybooleanOptionaltrueWhether published file messages should be stored in the channel's history. If storeInHistory is not specified, then the history configuration on the key is used.
ttlnumberOptional0How long the message should be stored in the channel's history. If not specified, defaults to the key set's retention value.
metaanyOptionalMetadata for the message.
customMessageTypestringOptionalA case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn-.

Examples: text, action, poll.

Basic Usage

const result = await pubnub.publishFile({
channel: "my_channel",
fileId: "...",
fileName: "cat_picture.jpg",
message: { field: "value" },
customMessageType: 'file-message',
});

Returns

{
timetoken: number
}

FileInput

FileInput represents a variety of possible inputs that represent a file in different environments.

Node.js

Using streams
{
stream: Readable,
name: string,
mimeType?: string
}
Using buffers
{
data: Buffer,
name: string,
mimeType?: string
}

Browsers

Using File API
File
Using strings
{
data: string,
name: string,
mimeType?: string
}
Using ArrayBuffer
{
data: ArrayBuffer,
name: string,
mimeType?: string
}

React and React Native

Using URI
{
uri: string,
name: string,
mimeType?: string
}

PubNub File

Internal representation of the file used by the SDK. Depending on the environment, different methods can be used to extract the file.

Methods supported in Node.js
  • file.toBuffer() returns Promise<Buffer>
  • file.toStream() returns Promise<Readable>
  • file.toString(encoding: string) returns a string encoded using encoding (if not available, defaults to utf8)
Methods supported in a browser
  • file.toFile() returns Promise<File>
  • file.toBlob() returns Promise<Blob>
  • file.toArrayBuffer() returns Promise<ArrayBuffer>
  • file.toString(encoding: string) returns a string encoded using encoding (if not available, defaults to utf8)
React and React Native
  • file.toBlob() returns Promise<Blob>
Last updated on