File Sharing API for 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 the file to a specified channel.
This method covers the entire process of sending a file, including preparation, uploading the file to a cloud storage service, and post-uploading messaging on a channel.
For the last messaging step, sendFile
internally calls the publishFile
method to publish a message on the channel.
The published message contains metadata about the file, such as the file identifier and name, enabling others on the channel to find out about the file and access it.
Method(s)
pubnub.sendFile(
params: SendFileParameters
): Promise<SendFileResult>;
Parameter | Description |
---|---|
params *Type: SendFileParameters | Parameters used to upload the file to a channel. |
SendFileParameters
Parameter | Description |
---|---|
channel *Type: string Default: n/a | Channel to send the file to. |
file *Type: FileInput Default: n/a | File to send. |
message Type: any Default: n/a | Optional message to attach to the file. |
storeInHistory Type: boolean Default: true | Whether 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. |
ttl Type: number Default: 0 | How long the message should be stored in the channel's history. If not specified, defaults to the key set's retention value. |
meta Type: any Default: n/a | Metadata for the message. |
customMessageType Type: string Default: n/a | A 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
const PubNub = require('pubnub');
const fs = require('fs');
// Initialize PubNub with demo keys
const pubnub = new PubNub({
publishKey: 'demo',
subscribeKey: 'demo',
userId: 'myUniqueUserId'
});
// Function to send a file to a channel
async function sendFileToChannel() {
try {
const myFile = fs.createReadStream('./cat_picture.jpg');
show all 29 linesReturns
{
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: ListFilesParameters
): Promise<ListFilesResult>;
Parameter | Description |
---|---|
params *Type: ListFilesParameters | Parameters used to retrieve the list of uploaded files. |
ListFilesParameters
Parameter | Description |
---|---|
channel *Type: string Default: n/a | Retrieve list of files for this channel. |
limit Type: number Default: 100 | Number of files to return. |
next Type: string Default: n/a | String 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;
Parameter | Description |
---|---|
params *Type: GetFileUrlParams | Parameters used to construct file URL. |
GetFileUrlParams
Parameter | Description |
---|---|
channel *Type: string | Channel that the file was sent to. |
id *Type: string | The file's unique identifier. |
name *Type: string | Name 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>;
Parameter | Description |
---|---|
params *Type: DownloadFileParams | Parameters used to download the file. |
DownloadFileParams
Parameter | Description |
---|---|
channel *Type: string Default: n/a | Channel that the file was sent to. |
id *Type: string Default: n/a | The file's unique identifier. |
name *Type: string Default: n/a | Name 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 linesReturns
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>;
Parameter | Description |
---|---|
params *Type: DeleteFileParams | Parameters used to delete the file. |
DeleteFileParams
Parameter | Description |
---|---|
channel *Type: string | Channel that the file was sent to. |
id *Type: string | The file's unique identifier. |
name *Type: string | Name 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 the uploaded file message to a specified channel.
This method is called internally by sendFile
as part of the file-sending process to publish the message with the file (already uploaded in a storage service) on a channel.
This message includes the file's unique identifier and name elements, which are needed to construct download links and inform channel subscribers that the file is available for download.
You can call this method when sendFile
fails and returns the status.operation === PNPublishFileMessageOperation
error.
In that case, you can use the data from the status
object to try again and use publishFile
to manually resend a file message to a channel without repeating the upload step.
Method(s)
pubnub.publishFile(
params: PublishFileParams
): Promise<PublishFileResult>;
Parameter | Description |
---|---|
params *Type: PublishFileParams | Parameters used to publish the file. |
PublishFileParams
Parameter | Description |
---|---|
channel *Type: string Default: n/a | Channel to which the file was sent. |
message Type: any Default: n/a | Optional message to attach to the file. |
fileId *Type: string Default: n/a | The file's unique identifier. |
fileName *Type: string Default: n/a | Name of the file. |
storeInHistory Type: boolean Default: true | Whether 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. |
ttl Type: number Default: 0 | How long the message should be stored in the channel's history. If not specified, defaults to the key set's retention value. |
meta Type: any Default: n/a | Metadata for the message. |
customMessageType Type: string Default: n/a | A 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()
returnsPromise<Buffer>
file.toStream()
returnsPromise<Readable>
file.toString(encoding: string)
returns a string encoded usingencoding
(if not available, defaults toutf8
)
Methods supported in a browser
file.toFile()
returnsPromise<File>
file.toBlob()
returnsPromise<Blob>
file.toArrayBuffer()
returnsPromise<ArrayBuffer>
file.toString(encoding: string)
returns a string encoded usingencoding
(if not available, defaults toutf8
)
React and React Native
file.toBlob()
returnsPromise<Blob>