Files API for PubNub Node.js 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
.
Send file
Description
Upload file / data to specified channel
.
Method(s)
pubnub.sendFile( params: SendFileParams, callback?: Function): Promise<SendFileResult>;
Parameter Type Required Description params
SendFileParams Yes Parameters used to upload the file to a channel. callback
Function Optional Function to be called with the status and result of the operation. If undefined, the function returns a Promise instead. 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';
const myFile = fs.createReadStream('./cat_picture.jpg');
const result = await pubnub.sendFile({
channel: 'my_channel',
file: { stream: myFile, name: 'cat_picture.jpg', mimeType: 'application/json' },
});
// in React and React Native
const result = await pubnub.sendFile({
channel: 'my_channel',
message: {
test: 'message',
value: 42
},
file: {
uri: imageUri,
name: 'cat_picture.jpg',
mimeType: 'image/jpeg',
},
});
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
Description
Retrieve list of files uploaded to Channel
.
Method(s)
pubnub.listFiles( params: ListFilesParams, callback?: Function): Promise<ListFilesResult>;
Parameter Type Required Description params
ListFilesParams Yes Parameters used to retrieve the list of uploaded files. callback
Function Optional Function to be called with the status and result of the operation. If undefined, the function returns a Promise instead.
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, callback?: Function): Promise<DownloadFileResult>;
Parameter Type Required Description params
DownloadFileParams Yes Parameters used to download the file. callback
Function Optional Function to be called with the status and result of the operation. If undefined, the function returns a Promise instead.
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'
const file = await pubnub.downloadFile({
channel: 'my_channel',
id: '...',
name: 'cat_picture.jpg',
});
const output = fs.createWriteStream('./cat_picture.jpg');
const fileStream = await file.toStream();
fileStream.pipe(output);
output.once('end', () => {
console.log('File saved to ./cat_picture.jpg');
});
// in React and React Native
const file = await pubnub.downloadFile({
channel: 'awesomeChannel',
id: imageId,
name: 'cat_picture.jpg'
});
let fileContent = await file.toBlob();
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
Description
Delete file from specified Channel
.
Method(s)
pubnub.deleteFile( params: DeleteFileParams, callback?: Function): Promise<DeleteFileResult>;
Parameter Type Required Description params
DeleteFileParams Yes Parameters used to delete the file. callback
Function Optional Function to be called with the status and result of the operation. If undefined, the function returns a Promise instead.
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, callback?: Function): Promise<PublishFileResult>;
Parameter Type Required Description params
PublishFileParams Yes Parameters used to publish the file. callback
Function Optional Function to be called with the status and result of the operation. If undefined, the function returns a Promise instead.
PublishFileParams
Parameter | Type | Required | Defaults | 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 returns a string encoded usingencoding
(if not available, defaults toutf8
)
React and React Native:
file.toBlob()
returnsPromise<Blob>