JavaScriptWebWebNode.jsPhoneGapReactReduxTitaniumVueJavaScript V4 Files API Reference for Realtime Apps

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.

Upload file / data to specified channel.
  1. ParameterTypeRequiredDescription
    params SendFileParamsYesParameters used to upload the file to a channel.
    callbackFunctionOptionalFunction to be called with the status and result of the operation.
    If undefined, the function returns a Promise instead.
    ParameterTypeRequiredDefaultDescription
    channelStringYesChannel to send the file to.
    file FileInputYesFile to send.
    messageAnyOptionalOptional message to attach to the file.
    cipherKeyStringOptionalfrom PubNub objectCipher key used to encrypt 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.
// 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',
  },
});
{
  name: string,
  id: string
}

  1. // 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',
    });
Retrieve list of files uploaded to Channel.
  1. ParameterTypeRequiredDescription
    params ListFilesParamsYesParameters used to retrieve the list of uploaded files.
    callbackFunctionOptionalFunction to be called with the status and result of the operation.
    If undefined, the function returns a Promise instead.
    ParameterTypeRequiredDefaultDescription
    channelStringYesRetrieve list of files for this channel.
    limitNumberOptional100Number of files to return.
    nextStringOptionalString token to get the next batch of files.
const result = await pubnub.listFiles({ channel: 'my_channel' });
{
  status: number,
  data: Array<{
    name: string,
    id: string,
    size: number,
    created: string
  }>,
  next: string,
  count: number,
}

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

  1. ParameterTypeRequiredDescription
    paramsGetFileUrlParamsYesParameters used to construct file URL..
    ParameterTypeRequiredDescription
    channelStringYesChannel that the file was sent to.
    idStringYesThe file's unique identifier.
    nameStringYesName of the file.
const result = pubnub.getFileUrl({ channel: 'my_channel', id: '...', name: '...' });
'https://ps.pndsn.com/v1/files/demo/channels/my_channel/files/12345678-1234-5678-123456789012/cat_picture.jpg'
Download file from specified Channel.
  1. ParameterTypeRequiredDescription
    params DownloadFileParamsYesParameters used to download the file.
    callbackFunctionOptionalFunction to be called with the status and result of the operation. If undefined, the function returns a Promise instead.
    ParameterTypeRequiredDefaultDescription
    channelStringYesChannel that the file was sent to.
    idStringYesThe file's unique identifier.
    nameStringYesName of the file.
    cipherKeyStringOptionalfrom PubNub objectCipher key used to decrypt the file.
// 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 instance of PubNubFile.


  1. const file = await pubnub.downloadFile({
      channel: 'my_channel',
      id: '...',
      name: 'cat_picture.jpg',
      cipherKey: 'myCipherKey',
    });
Delete file from specified Channel.
  1. ParameterTypeRequiredDescription
    params DeleteFileParamsYesParameters used to delete the file.
    callbackFunctionOptionalFunction to be called with the status and result of the operation. If undefined, the function returns a Promise instead.
    ParameterTypeRequiredDescription
    channelStringYesChannel that the file was sent to.
    idStringYesThe file's unique identifier.
    nameStringYesName of the file.
const result = await pubnub.deleteFile({
  channel: 'my_channel',
  id: '...',
  name: 'cat_picture.jpg',
});

Example of successful deletion:

{
  status: 200
}
Publish file message from specified Channel.
  1. ParameterTypeRequiredDescription
    params PublishFileParamsYesParameters used to publish the file.
    callbackFunctionOptionalFunction to be called with the status and result of the operation.
    If undefined, the function returns a Promise instead.
    ParameterTypeRequiredDefaultsDescription
    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.
const result = await pubnub.publishFile({
  channel: 'my_channel',
  fileId: '...',
  fileName: 'cat_picture.jpg',
  message: { field: 'value' },
});
{
  timetoken: number
}
FileInput represents a variety of possible inputs that represent a file in different environments.
Using streams:

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

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

{
    data: string,
    name: string,
    mimeType?: string
}
Using ArrayBuffer:

{
    data: ArrayBuffer,
    name: string,
    mimeType?: string 
}
Using URI

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

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 returns a string encoded using encoding (if not available, defaults to utf8)

  • React and React Native:
    • file.toBlob() returns Promise