---
source_url: https://www.pubnub.com/docs/sdks/asyncio/api-reference/files
title: File Sharing API for Python-Asyncio SDK
updated_at: 2026-06-08T10:22:36.939Z
sdk_name: PubNub Python Asyncio SDK
---

> 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 Python-Asyncio SDK

PubNub Python Asyncio SDK

Install:

```bash
pip install pubnub
```

Use the Files API to upload and share files up to 5 MB. Common use cases include social apps that share images and healthcare apps that share medical records.

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

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, `send_file` internally calls the [publish_file_message](#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)

```python
pubnub.send_file()
    .channel(channel) \
    .file_name(file_name) \
    .message(message) \
    .should_store(should_store) \
    .ttl(ttl) \
    .file_object(file_object) \
    .cipher_key(cipher_key) \
    .future()
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | String | Yes |  | Channel for the file. |
| file_name | String | Yes |  | Name of the file to send. |
| file_object | bytes | Yes |  | Input stream with file content. |
| cipherKey | String | Optional | `PNConfiguration#cipherKey` | Key used to encrypt uploaded data. If not provided, the `cipherKey` in `PNConfiguration` is used if configured. |
| ttl | Integer | Optional |  | How long the message should be stored in the channel's storage. |
| should_store | Boolean | Optional | `True` | Whether to store the published `file message` in the `channel` history. |
| message | Dictionary | Optional |  | Message to send along with the file to the specified `channel`. |
| meta | Dictionary | Optional |  | Metadata object that can be used with the filtering capability. |

### 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.
:::

```python
import asyncio
import os
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub_asyncio import PubNubAsyncio
from pubnub.exceptions import PubNubException

async def send_file(pubnub: PubNubAsyncio):
    try:
        with open("knights_of_ni.jpg", "rb") as fd:
            # Send a file with additional options
            envelope = await pubnub.send_file() \
                .channel("test_channel") \
                .file_name("knights_of_ni.jpg") \
                .message({"test_message": "test"}) \
                .should_store(True) \
                .ttl(222) \
                .file_object(fd) \
                .cipher_key("secret") \
                .future()

            if envelope.status.is_error():
                print("Error sending file")
            else:
                print(f"File sent successfully: {envelope.result.name}")

    except PubNubException as e:
        print(f"Error: {e}")
    except FileNotFoundError:
        print("File not found, please check the file path")

if __name__ == "__main__":
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    # Configuration for PubNub instance
    pn_config = PNConfiguration()
    pn_config.subscribe_key = os.getenv('SUBSCRIBE_KEY', 'demo')
    pn_config.publish_key = os.getenv('PUBLISH_KEY', 'demo')
    pn_config.user_id = "my_custom_user_id"

    pubnub = PubNubAsyncio(pn_config)

    try:
        loop.run_until_complete(send_file(pubnub))
    finally:
        loop.run_until_complete(pubnub.stop())
        loop.close()
```

### Returns

The `send_file()` operation returns a `PNSendFileResult` with the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `name` | String | Name of the uploaded file. |
| `file_id` | String | ID of the uploaded file. |
| `timestamp` | String | The timetoken at which the message was published. |

### Other examples

#### 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 `send_file` 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.
:::

```python
message = {
  "text": "Check out this file!",
  "pn_apns": {
      "aps": {
          "alert": {"title": "New File", "body": "A file was shared"}
      },
      "pn_push": [{
          "targets": [{"topic": "com.yourapp.bundleid", "environment": "production"}],
          "version": "v2"
      }]
  },
  "pn_fcm": {
      "notification": {"title": "New File", "body": "A file was shared"}
  }
}

with open("example.txt", "rb") as file_object:
  result = pubnub.send_file()       .channel("my-channel")       .file_name("example.txt")       .file_object(file_object)       .message(message)       .sync()
```

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)

```python
pubnub.list_files().channel(String)
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: n/a | Channel to get the list of files. |
| `limit`Type: IntDefault: n/a | The number of elements to return. |
| `next`Type: StringDefault: n/a | Random string returned from the server indicating a specific position in a dataset. Used for forward pagination to fetch the next page and continue from where you left off. |

### Sample code

```python
envelope = await pubnub.list_files().channel("test_channel").limit(10).next("XYZ....ABC").future()
```

### Returns

The `list_files()` operation returns a `PNGetFilesResult` with the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `next` | String | Random string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off. |
| `count` | Int | Number of files returned. |
| `data` | List | `List` of channel files. |

`data` contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `id` | Long | ID of the uploaded file. |
| `name` | String | Name of the uploaded file. |
| `size` | String | Size of the uploaded file. |
| `created` | String | Time of creation. |

## Get file URL

Generate a URL to download a file from the target `channel`.

### Method(s)

```python
pubnub.get_file_url() \
    .channel(String) \
    .file_id(String) \
    .file_name(String)
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: String | Name of `channel` to which the file has been uploaded. |
| `file_name` *Type: String | Name under which the uploaded file is stored. |
| `file_id` *Type: String | Unique identifier for the file, assigned during upload. |

### Sample code

```python
envelope = await pubnub.get_file_url().\
    channel("test_channel").\
    file_id("d9515cb7-48a7-41a4-9284-f4bf331bc770").\
    file_name("knights_of_ni.jpg").future()
```

### Returns

The `get_file_url()` operation returns a `PNGetFileDownloadURLResult` with the following property:

| Property Name | Type | Description |
| --- | --- | --- |
| `file_url` | String | `URL` to be used to download the requested file. |

## Download file

Download a file from the specified `channel`.

### Method(s)

```python
pubnub.download_file() \
    .channel(String) \
    .file_id(String) \
    .file_name(String)
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: String | Name of `channel` to which the file has been uploaded. |
| `file_name` *Type: String | Name under which the uploaded file is stored. |
| `file_id` *Type: String | Unique identifier for the file, assigned during upload. |
| `cipher_key`Type: String | Key used to decrypt downloaded data. If not provided, the SDK uses the `cipher_key` from the `PNConfiguration`. |

### Sample code

```python
download_envelope = await pubnub.download_file().\
    channel("test_channel").\
    file_id("fileId").\
    file_name("knights_of_ni.jpg").future()
```

### Returns

The `download_file()` operation returns a `PNDownloadFileResult` with the following property:

| Property Name | Type | Description |
| --- | --- | --- |
| `data` | bytes | Python bytes object. |

## Delete file

Delete a file from the specified `channel`.

### Method(s)

```python
pubnub.delete_file() \
    .channel(String) \
    .file_id(String) \
    .file_name(String)
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: String | The `channel` from which to delete the file. |
| `file_id` *Type: String | Unique identifier of the file to be deleted. |
| `file_name` *Type: String | Name of the file to be deleted. |

### Sample code

```python
envelope = await pubnub.delete_file().\
    channel("test_channel").\
    file_id("fileId").\
    file_name("knights_of_ni.jpg").future()
```

### Returns

The `delete_file()` operation returns a `PNDeleteFileResult` with the following property:

| Property Name | Type | Description |
| --- | --- | --- |
| `status` | Int | Returns a status code. |

## Publish file message

Publish the uploaded file message to a specified channel.

This method is called internally by [send_file](#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 `send_file` 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 `publish_file_message` to manually resend a file message to a channel without repeating the upload step.

### Method(s)

```python
pubnub.publish_file_message() \
    .channel(String) \
    .meta(Dictionary) \
    .message(Dictionary) \
    .file_id(String) \
    .file_name(String) \
    .should_store(Boolean) \
    .ttl(Integer)
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: n/a | Name of the `channel` to publish the file message. |
| `file_name` *Type: StringDefault: n/a | Name of the file. |
| `file_id` *Type: StringDefault: n/a | Unique identifier of the file. |
| `message`Type: DictionaryDefault: n/a | The payload. |
| `meta`Type: DictionaryDefault: n/a | Metadata object that can be used with the filtering capability. |
| `should_store`Type: BooleanDefault: `True` | Set to `False` to not store this message in history. By default, messages are stored according to the retention policy set on your key. |
| `ttl`Type: IntegerDefault: `0` | How long the message is stored in the channel's history. If not specified, defaults to the key set's retention value. |

### Sample code

```python
envelope = await pubnub.publish_file_message().\
    channel("test_channel").\
    meta({"test": "test"}).\
    message({"test_message": "test"}).\
    file_id("fileID").\
    file_name("knights_of_ni.jpg").\
    ttl(22).future()
```

### Returns

The `publish_file_message()` operation returns a `PNPublishFileMessageResult` with the following property:

| Property Name | Type | Description |
| --- | --- | --- |
| `timestamp` | String | The timetoken at which the message was published. |