---
source_url: https://www.pubnub.com/docs/sdks/javascript/api-reference/files
title: File Sharing API for JavaScript SDK
updated_at: 2026-06-04T11:11:55.314Z
sdk_name: PubNub JavaScript SDK
sdk_version: 11.0.1
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# File Sharing API for JavaScript SDK

PubNub JavaScript SDK, use the latest version: 11.0.1

Install:

```bash
npm install pubnub@11.0.1
```

You can upload and share files up to 5 MB on PubNub. Common uses include sharing images in chat apps and documents in healthcare.

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`.

:::note Supported and recommended asynchronous patterns
PubNub supports [Callbacks, Promises, and Async/Await](https://javascript.info/async) 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](https://javascript.info/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](#publish-file-message) 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.

For details on the method that publishes the file message, see [Publish file message](#publish-file-message).

### Method(s)

```javascript
pubnub.sendFile(
  params: SendFileParameters
): Promise<SendFileResult>;
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| params | SendFileParameters | Yes |  | Parameters used to upload the file to a channel. |

#### SendFileParameters

| Parameter | Description |
| --- | --- |
| `channel` *Type: stringDefault: n/a | Channel to send the file to. |
| `file` *Type: [FileInput](#fileinput)Default: n/a | File to send. |
| `message`Type: anyDefault: n/a | Optional message to attach to the file. |
| `storeInHistory`Type: booleanDefault: `true` | Whether to store published file messages in the channel's history. If `storeInHistory` is not specified, the history configuration on the key is used. |
| `ttl`Type: numberDefault: 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: anyDefault: n/a | Metadata for the message. |
| `customMessageType`Type: stringDefault: 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`. |

:::warning Deprecated parameter
The `cipherKey` parameter in this method is deprecated. We recommend that you configure the [crypto module](https://www.pubnub.com/docs/sdks/javascript/api-reference/configuration#cryptomodule) 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.
:::

### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```javascript
import PubNub from 'pubnub';
import fs from 'fs';
// Initialize PubNub with your keys
const pubnub = new PubNub({
  publishKey: 'YOUR_PUBLISH_KEY',
  subscribeKey: 'YOUR_SUBSCRIBE_KEY',
  userId: 'YOUR_USER_ID',
});
```

```javascript
// Function to send a file to a channel
try {
  // in node.js, make sure to import 'fs'
  // and use the createReadStream method to read the file
  const myFile = fs.createReadStream('./cat_picture.jpg');

  const response = await pubnub.sendFile({
    channel: 'my_channel',
    file: { stream: myFile, name: 'cat_picture.jpg', mimeType: 'image/jpeg' },
    customMessageType: 'file-message',
  });

  console.log('File sent successfully:', response);
} catch (error) {
  console.error(
    `Error sending file: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}
```

### Returns

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

### Other examples

#### Usage with a message and custom cipher key

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

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

  const response = await pubnub.sendFile({
    channel: 'my_channel',
    message: 'Look at this picture!',
    file: { data: myFile, name: 'cat_picture.jpg', mimeType: 'application/json' },
    cipherKey: 'myCipherKey',
  });
  console.log('File sent successfully:', response);
} catch (error) {
  console.error(
    `Error sending file: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}
```

#### Send file with push notification

:::tip Trigger push notifications when sharing files
To send mobile push notifications when sharing a file, include `pn_apns` (for iOS) and/or `pn_fcm` (for Android) payloads in the `message` parameter of the `sendFile` method.
When PubNub detects these reserved keys, it automatically forwards the push notification to the appropriate push service (APNs or FCM) for all devices registered on the channel.
:::

```javascript
// Create a notification payload with title and body
const notificationPayload = PubNub.notificationPayload('New File', 'A file was shared');

// Configure APNS2 with your specific topic and environment
notificationPayload.apns.configurations = [
{
  targets: [
    {
      topic: 'com.yourapp.bundleid',
      environment: 'production',
    },
  ],
},
];

// Build the payload for both APNS2 and FCM
const pushPayload = notificationPayload.buildPayload(['apns2', 'fcm']);

const fileMessage = {
...pushPayload,
text: 'Check out this file!',
};

await pubnub.sendFile({
channel: 'my-channel',
file: myFile,
message: fileMessage,
});
```

For more details on push notification payload structure, see the [iOS Push](https://www.pubnub.com/docs/general/push/ios) and [Android Push](https://www.pubnub.com/docs/general/push/android) documentation. To prevent the sender from receiving their own push notification, add their device token to `excluded_devices` in the `pn_push` targets.

## List channel files

Retrieve a list of files uploaded to a `channel`.

### Method(s)

```javascript
pubnub.listFiles(
  params: ListFilesParameters
): Promise<ListFilesResult>;
```

| Parameter | Description |
| --- | --- |
| `params` *Type: [ListFilesParameters](#listfilesparameters) | Parameters used to retrieve the list of uploaded files. |

#### ListFilesParameters

| Parameter | Description |
| --- | --- |
| `channel` *Type: stringDefault: n/a | Retrieve list of files for this channel. |
| `limit`Type: numberDefault: 100 | Number of files to return. |
| `next`Type: stringDefault: n/a | String token to get the next batch of files. |

### Sample code

```javascript
try {
  const response = await pubnub.listFiles({ channel: 'my_channel' });
  console.log('Files listed successfully:', response);
} catch (error) {
  console.error(
    `Error listing files: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}
```

### Returns

```javascript
{
  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)

```javascript
pubnub.getFileUrl(
  params: GetFileUrlParams
): string;
```

| Parameter | Description |
| --- | --- |
| `params` *Type: [GetFileUrlParams](#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. |

### Sample code

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

### Returns

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

## Download file

Download a file from the specified `channel`.

### Method(s)

```javascript
pubnub.downloadFile(
  params: DownloadFileParams
): Promise<DownloadFileResult>;
```

| Parameter | Description |
| --- | --- |
| `params` *Type: [DownloadFileParams](#downloadfileparams) | Parameters used to download the file. |

#### DownloadFileParams

| Parameter | Description |
| --- | --- |
| `channel` *Type: stringDefault: n/a | Channel that the file was sent to. |
| `id` *Type: stringDefault: n/a | The file's unique identifier. |
| `name` *Type: stringDefault: n/a | Name of the file. |

:::warning Deprecated parameter
The `cipherKey` parameter in this method is deprecated. We recommend that you configure the [crypto module](https://www.pubnub.com/docs/sdks/javascript/api-reference/configuration#cryptomodule) 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.
:::

### Sample code

```javascript
// In Node.js using streams:
// import fs from 'fs'
try {
  const downloadFileResponse = await pubnub.downloadFile({
    channel: 'my_channel',
    id: '...',
    name: 'cat_picture.jpg',
  });

  const output = fs.createWriteStream('./cat_picture.jpg');
  const fileStream = await downloadFileResponse.toStream();

  fileStream.pipe(output);

  output.once('end', () => {
    console.log('File saved to ./cat_picture.jpg');
  });
} catch (error) {
  console.error(
    `Error downloading file: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}
```

```javascript
// in React and React Native
let file;
try {
  file = await pubnub.downloadFile({
    channel: 'awesomeChannel',
    id: 'imageId',
    name: 'cat_picture.jpg',
  });
} catch (error) {
  console.error(
    `Error downloading file: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}
const fileContent = await file!.toBlob();
```

```javascript
// In browser
// download the intended file
const downloadFile = async () => {
  try {
    const file = await pubnub.downloadFile({
      channel: 'my_channel',
      id: '...',
      name: 'cat_picture.jpg',
    });

    // have proper html element to display the file
    const myImageTag = document.createElement('img');
    myImageTag.src = URL.createObjectURL(await file!.toFile());

    // attach the file content to the html element
    document.body.appendChild(myImageTag);
  } catch (error) {
    console.error(
      `Download file error: ${error}.${
        (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
      }`,
    );
  }
};
```

### Returns

Returns instance of [PubNubFile](#pubnub-file).

### Other examples

#### Usage with custom cipher key

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

## Delete file

Delete a file from the specified `channel`.

### Method(s)

```javascript
pubnub.deleteFile(
  params: DeleteFileParams
): Promise<DeleteFileResult>;
```

| Parameter | Description |
| --- | --- |
| `params` *Type: [DeleteFileParams](#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. |

### Sample code

```javascript
try {
  const deleteFileResponse = await pubnub.deleteFile({
    channel: 'my_channel',
    id: '...',
    name: 'cat_picture.jpg',
  });
  console.log('File deleted successfully:', deleteFileResponse);
} catch (error) {
  console.error(
    `Error deleting file: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}
```

### Returns

Example of successful deletion:

```javascript
{
  status: 200
}
```

## Publish file message

Publish the uploaded file message to a specified channel.

This method is called internally by [sendFile](#send-file) 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)

```javascript
pubnub.publishFile(
  params: PublishFileParams
): Promise<PublishFileResult>;
```

| Parameter | Description |
| --- | --- |
| `params` *Type: [PublishFileParams](#publishfileparams) | Parameters used to publish the file. |

#### PublishFileParams

| Parameter | Description |
| --- | --- |
| `channel` *Type: stringDefault: n/a | Channel to which the file was sent. |
| `message`Type: anyDefault: n/a | Optional message to attach to the file. |
| `fileId` *Type: stringDefault: n/a | The file's unique identifier. |
| `fileName` *Type: stringDefault: n/a | Name of the file. |
| `storeInHistory`Type: booleanDefault: `true` | Whether to store published file messages in the channel's history. If `storeInHistory` is not specified, the history configuration on the key is used. |
| `ttl`Type: numberDefault: 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: anyDefault: n/a | Metadata for the message. |
| `customMessageType`Type: stringDefault: 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`. |

### Sample code

```javascript
try {
  const fileMessageResponse = await pubnub.publishFile({
    channel: 'my_channel',
    fileId: '...',
    fileName: 'cat_picture.jpg',
    message: { field: 'value' },
    customMessageType: 'file-message',
  });
  console.log('File message published successfully:', fileMessageResponse);
} catch (error) {
  console.error(
    `Error publishing file message: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}
```

### Returns

```javascript
{
  timetoken: number
}
```

## FileInput

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

#### Node.js

##### Using streams

```javascript
{
    stream: Readable,
    name: string,
    mimeType?: string
}
```

##### Using buffers

```javascript
{
    data: Buffer,
    name: string,
    mimeType?: string
}
```

#### Browsers

##### Using File API

```javascript
File
```

##### Using strings

```javascript
{
    data: string,
    name: string,
    mimeType?: string
}
```

##### Using ArrayBuffer

```javascript
{
    data: ArrayBuffer,
    name: string,
    mimeType?: string
}
```

#### React and React Native

##### Using URI

```javascript
{
    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>`