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
Description
Upload file / data to specified channel
.
Method(s)
pubnub.sendFile(
params: SendFileParams
): Promise<SendFileResult>;
Parameter | Type | Required | Description |
---|---|---|---|
params | SendFileParams | Yes | Parameters used to upload the file to a channel. |
SendFileParams
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
channel | string | Yes | Channel to send the file to. | |
file | FileInput | Yes | File to send. | |
message | any | Optional | Optional message to attach to the file. | |
cipherKey | string | Optional | from PubNub object | Cipher key used to encrypt the file. |
storeInHistory | boolean | Optional | 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 | number | Optional | 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 | any | Optional | Metadata for the message. |
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,
});
});
// in Node.js
import fs from 'fs';
show all 35 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
Description
Retrieve list of files uploaded to Channel
.
Method(s)
pubnub.listFiles(
params: ListFilesParams
): Promise<ListFilesResult>;
Parameter | Type | Required | Description |
---|---|---|---|
params | ListFilesParams | Yes | Parameters used to retrieve the list of uploaded files. |
ListFilesParams
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
channel | string | Yes | Retrieve list of files for this channel. | |
limit | number | Optional | 100 | Number of files to return. |
next | string | Optional | 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
Description
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 | Type | Required | Description |
---|---|---|---|
params | GetFileUrlParams | Yes | Parameters used to construct file URL. |
GetFileUrlParams
Parameter | Type | Required | Description |
---|---|---|---|
channel | string | Yes | Channel that the file was sent to. |
id | string | Yes | The file's unique identifier. |
name | string | Yes | 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
Description
Download file from specified Channel
.
Method(s)
pubnub.downloadFile(
params: DownloadFileParams
): Promise<DownloadFileResult>;
Parameter | Type | Required | Description |
---|---|---|---|
params | DownloadFileParams | Yes | Parameters used to download the file. |
DownloadFileParams
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
channel | string | Yes | Channel that the file was sent to. | |
id | string | Yes | The file's unique identifier. | |
name | string | Yes | Name of the file. | |
cipherKey | string | Optional | from PubNub object | Cipher key used to decrypt the file. |
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
Description
Delete file from specified Channel
.
Method(s)
pubnub.deleteFile(
params: DeleteFileParams
): Promise<DeleteFileResult>;
Parameter | Type | Required | Description |
---|---|---|---|
params | DeleteFileParams | Yes | Parameters used to delete the file. |
DeleteFileParams
Parameter | Type | Required | Description |
---|---|---|---|
channel | string | Yes | Channel that the file was sent to. |
id | string | Yes | The file's unique identifier. |
name | string | Yes | 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
Description
Publish file message from specified Channel
.
Method(s)
pubnub.publishFile(
params: PublishFileParams
): Promise<PublishFileResult>;
Parameter | Type | Required | Description |
---|---|---|---|
params | PublishFileParams | Yes | Parameters used to publish the file. |
PublishFileParams
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
channel | string | Yes | Channel to which the file was sent. | |
message | any | Optional | Optional message to attach to the file. | |
fileId | string | Yes | The file's unique identifier. | |
fileName | string | Yes | Name of the file. | |
storeInHistory | boolean | Optional | 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 | number | Optional | 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 | any | Optional | Metadata for the message. |
Basic Usage
const result = await pubnub.publishFile({
channel: "my_channel",
fileId: "...",
fileName: "cat_picture.jpg",
message: { field: "value" },
});
Returns
{
timetoken: number
}
FileInput
Description
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>