---
source_url: https://www.pubnub.com/docs/sdks/kotlin/api-reference/files
title: File Sharing API for Kotlin SDK
updated_at: 2026-06-19T11:37:42.968Z
sdk_name: PubNub Kotlin SDK
sdk_version: 13.4.0
---

> 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 Kotlin SDK

PubNub Kotlin SDK, use the latest version: 13.4.0

Install:

```bash
Add PubNub dependency to your build@13.4.0
```

:::warning Breaking changes in v9.0.0
PubNub Kotlin SDK version 9.0.0 unifies the codebases for Kotlin and [Java](https://www.pubnub.com/docs/sdks/java) SDKs, introduces a new way of instantiating the PubNub client, and changes asynchronous API callbacks and emitted [status events](https://www.pubnub.com/docs/sdks/kotlin/status-events). These changes can impact applications built with previous versions (< `9.0.0` ) of the Kotlin SDK.
For more details about what has changed, refer to [Java/Kotlin SDK migration guide](https://www.pubnub.com/docs/sdks/kotlin/migration-guides/kotlin-v9-migration-guide).
:::

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

:::tip Request execution
Most PubNub Kotlin SDK method invocations return an Endpoint object, which allows you to decide whether to perform the operation synchronously or asynchronously.
You must invoke the `.sync()` or `.async()` method on the Endpoint to execute the request, or the operation **will not** be performed.
```kotlin
val channel = pubnub.channel("channelName")
channel.publish("This SDK rules!").async { result ->
    result.onFailure { exception ->
        // Handle error
    }.onSuccess { value ->
        // Handle successful method result
    }
}
```
:::

## 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 [publishFileMessage](#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)

```kotlin
pubnub.sendFile(
    channel: String,
    fileName: String,
    inputStream: InputStream,
    message: Any? = null,
    meta: Any? = null,
    ttl: Int? = null,
    shouldStore: Boolean? = null
    customMessageType: String
)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | String | Yes |  | Channel for the file. |
| fileName | String | Yes |  | Name of the file to send. |
| inputStream | InputStream | Yes |  | Input stream with file content. |
| message | Any? | Optional |  | Message to send along with the file to the specified `channel`. |
| meta | Any? | Optional |  | Metadata object which can be used with the filtering ability. |
| ttl | Int? | Optional |  | How long the message should be stored in the channel's storage. |
| shouldStore | Boolean? | Optional | `true` | Whether to store the published `file message` in the `channel` history. |
| customMessageType | String | Optional |  | 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/kotlin/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.
:::

```kotlin
import com.pubnub.api.PubNub
import com.pubnub.api.UserId
import com.pubnub.api.v2.PNConfiguration
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream

/**
 * This example demonstrates how to use the sendFile method in PubNub Kotlin SDK.
 *
 * The sendFile method allows you to upload files (up to 5MB) to a PubNub channel
 * where they can be shared with subscribers.
 */
fun main() {
    println("PubNub sendFile() Example")
    println("========================")

    // 1. Configure PubNub
    val userId = UserId("file-upload-demo-user")
    val config = PNConfiguration.builder(userId, "demo").apply {
        publishKey = "demo"
    }.build()

    // 2. Create PubNub instance
    val pubnub = PubNub.create(config)

    try {
        // 3. First, create a temporary test file (in a real app, you'd use an existing file)
        println("Creating a temporary test file...")
        val tempFile = File.createTempFile("pubnub_test_", ".txt")
        tempFile.deleteOnExit() // Clean up when JVM exits

        // 4. Write some content to the test file
        FileOutputStream(tempFile).use { output ->
            output.write("This is a test file for PubNub file upload demo.".toByteArray())
        }

        println("Temporary file created at: ${tempFile.absolutePath}")

        // 5. Create file input stream
        val inputStream = FileInputStream(tempFile)

        println("Uploading file to PubNub...")

        // 6. Send the file to PubNub
        pubnub.sendFile(
            channel = "demo-file-channel", // The channel to upload the file to
            fileName = "test_document.txt", // The name to give the file when uploaded
            inputStream = inputStream, // The file data to upload
            message = mapOf( // Optional message to accompany the file
                "text" to "Here's a test document!",
                "type" to "document"
            ),
            customMessageType = "file-message", // Optional custom message type
            meta = mapOf( // Optional metadata for filtering
                "sender" to "demo-user",
                "app" to "kotlin-example"
            )
            // Additional optional parameters:
            // ttl = 24*60*60,                 // Time-to-live in seconds (24 hours)
            // shouldStore = true,             // Whether to store in history (default true)
        ).async { result ->
            result.onSuccess { response ->
                println("\nFile upload successful!")
                println("  • Timetoken: ${response.timetoken}")
                println("  • File ID: ${response.file.id}")
                println("  • File Name: ${response.file.name}")

                // 7. Get a URL for downloading the file
                pubnub.getFileUrl(
                    channel = "demo-file-channel",
                    fileName = response.file.name,
                    fileId = response.file.id
                ).async { urlResult ->
                    urlResult.onSuccess { urlResponse ->
                        println("  • Download URL: ${urlResponse.url}")

                        // 8. Clean up resources
                        inputStream.close()
                        pubnub.destroy() // Clean up PubNub resources
                    }.onFailure { exception ->
                        println("Error getting file URL: ${exception.message}")
                        inputStream.close()
                        pubnub.destroy()
                    }
                }
            }.onFailure { exception ->
                println("Error uploading file: ${exception.message}")
                inputStream.close()
                pubnub.destroy()
            }
        }

        println("\nFile upload initiated. Check console for results.")
        println("The async results will appear above this message.")

        // Keep the program running to allow async operations to complete
        Thread.sleep(5000)
    } catch (e: Exception) {
        println("Error: ${e.message}")
        e.printStackTrace()
    }
}
```

### Response

```kotlin
{
  "timetoken": 15957709330808500,
  "status": 200,
  "file": {
      "id": "d9515cb7-48a7-41a4-9284-f4bf331bc770",
      "name": "cat_picture.jpg"
  }
}
```

### Returns

The `sendFile()` operation returns a `PNFileUploadResult` which contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `timetoken` | Long | A representation of the timetoken when the message was published. |
| `status` | Int | Remote call return code. |
| `file` | PNBaseFile | Uploaded file information. |

`PNBaseFile` contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `id` | Long | Id of the uploaded file. |
| `name` | String | Name of the upload file. |

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

```kotlin
 val pushPayloadHelper = PushPayloadHelper().apply {
      // APNS (iOS)
      apnsPayload = APNSPayload().apply {
          aps = APNSPayload.APS().apply {
              alert = mapOf("title" to "New File", "body" to "A file was shared")
              sound = "default"
          }
          apns2Configurations = listOf(
              APNSPayload.APNS2Configuration().apply {
                  targets = listOf(
                      APNSPayload.APNS2Configuration.Target().apply {
                          topic = "com.yourapp.bundleid"
                          environment = PNPushEnvironment.PRODUCTION
                      }
                  )
                  version = "v2"
                  authMethod = APNSPayload.APNS2Configuration.APNS2AuthMethod.TOKEN
              }
          )
      }

      // FCM (Android)
      fcmPayloadV2 = PushPayloadHelper.FCMPayloadV2().apply {
          notification = PushPayloadHelper.FCMPayloadV2.Notification().apply {
              title = "New File"
              body = "A file was shared"
          }
          data = mapOf("type" to "file_shared", "channel" to "my-channel")
      }

      // Common payload
      commonPayload = mapOf("text" to "Check out this file!")
  }

  val message = pushPayloadHelper.build()
  val fileInputStream: InputStream = FileInputStream("path/to/your/file.txt")
  pubnub.sendFile(
      channel = "my-channel",
      fileName = "example.txt",
      inputStream = fileInputStream,
      message = message
  ).async { result ->
      result.onSuccess { res ->
          println("File ID: ${res.file.id}")
      }.onFailure { ex ->
          println("Error: ${ex.message}")
      }
  }
```

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)

```kotlin
pubnub.listFiles()
    channel: String,
    limit: Int,
    next: String?
)
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: n/a | Channel to get list of files. |
| `limit`Type: IntDefault: 100 | Number of files to return. Minimum value is 1, and maximum is 100. |
| `next`Type: String?Default: n/a | 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. |

### Sample code

```kotlin
pubnub.listFiles(
    channel = "my_channel"
).async { result ->
    result.onFailure { exception ->
        // Handle error
    }.onSuccess { value ->
        // Handle successful method result
    }
}
```

### Response

```kotlin
{
  "data":[
      {
      "name":"cat_picture.jpg",
      "id":"fileId",
      "size":25778,
      "created":"202007 - 26T13:42:06Z"
      }],
   "status": 200
   "totalCount": 1,
   "next": null,
   "prev": null
}
```

### Returns

The `listFiles()` operation returns a `PNListFilesResult` which contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `timetoken` | Long | A representation of the timetoken when the message was published. |
| `status` | Int | Remote call return code. |
| `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`<PNUploadedFile>` | List of channel files. |

`PNUploadedFile` contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `id` | Long | Id of the uploaded file. |
| `name` | String | Name of the upload file. |
| `size` | Int | 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)

```kotlin
pubnub.getFileUrl(
    channel: String,
    fileName: String,
    fileId: String
)
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: n/a | Name of channel to which the file has been uploaded. |
| `fileName` *Type: StringDefault: n/a | Name under which the uploaded file is stored. |
| `fileId` *Type: StringDefault: n/a | Unique identifier for the file, assigned during upload. |

### Sample code

```kotlin
pubnub.getFileUrl(
    channel = "my_channel",
    fileName = "cat_picture.jpg",
    fileId = "someFileId"
).async { result ->
    result.onFailure { exception ->
        // Handle error
    }.onSuccess { value ->
        // Handle successful method result
    }
}
```

### Response

```kotlin
{
    "url" : http://ps.pndsn.com/v1/files/demo/channels/my_channel/files/fileID/cat_picture.jpg?pnsdk=PubNub-kotlin-Unified/4.32.0&timestamp=1595771548&uuid=someUuid
}
```

### Returns

The `getFileUrl()` operation returns a `PNFileUrlResult` which contains the following properties:

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

## Download file

Download the specified file.

### Method(s)

```kotlin
pubnub.downloadFile(
    channel: String,
    fileName: String,
    fileId: String
)
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: n/a | Name of channel to which the file has been uploaded. |
| `fileName` *Type: StringDefault: n/a | Name under which the uploaded file is stored. |
| `fileId` *Type: StringDefault: n/a | Unique identifier for the file, assigned during upload. |

:::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/kotlin/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

```kotlin
pubnub.downloadFile(
    channel = "my_channel",
    fileName = "cat_picture.jpg",
    fileId = "d9515cb7-48a7-41a4-9284-f4bf331bc770"
).async { result ->
    result.onFailure { exception ->
        // Handle error
    }.onSuccess { value ->
        // Handle successful method result
    }
}
```

### Response

```kotlin
{
    "fileName": "cat_picture.jpg",
    "byteStream": <file data>
}
```

### Returns

The `downloadFile()` operation returns a `PNDownloadFileResult` which contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `fileName` | string | Name of the downloaded file. |
| `byteStream` | InputStream | Input stream containing all bytes of the downloaded file. |

## Delete file

Delete a file from the specified `channel`.

### Method(s)

```kotlin
pubnub.deleteFile(
    channel: String,
    fileName: String,
    fileId: String
)
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: n/a | The channel from which to delete the file. |
| `fileName` *Type: StringDefault: n/a | Name of the file to be deleted. |
| `fileId` *Type: StringDefault: n/a | Unique identifier of the file to be deleted. |

### Sample code

```kotlin
pubnub.deleteFile(
    channel = "my_channel",
    fileName = "cat_picture.jpg",
    fileId = "someFileId"
).async { result ->
    result.onFailure { exception ->
        // Handle error
    }.onSuccess { value ->
        // Handle successful method result
    }
}
```

### Response

```kotlin
{
    "status": 200
}
```

### Returns

The `deleteFile()` operation returns a `PNDeleteFileResult` which contains 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 [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 `publishFileMessage` to manually resend a file message to a channel without repeating the upload step.

### Method(s)

```kotlin
pubnub.publishFileMessage(
    channel: String,
    fileName: String,
    fileId: String,
    message: Any?,
    meta: Any?,
    shouldStore: Boolean,
    customMessageType: String
)
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: n/a | Name of channel to publish file message. |
| `fileName` *Type: StringDefault: n/a | Name of the `file`. |
| `fileId` *Type: StringDefault: n/a | Unique identifier of the file. |
| `message`Type: Any?Default: n/a | The payload. |
| `meta`Type: Any?Default: n/a | Metadata object which can be used with the filtering capability. |
| `shouldStore`Type: BooleanDefault: true | Whether to store this message in history. Set to `false` to not store it. By default, messages are stored according to the retention policy you set on your key. |
| `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

```kotlin
pubnub.publishFileMessage(
    channel = "my_channel",
    fileName = "cat_picture.jpg",
    fileId = "d9515cb7-48a7-41a4-9284-f4bf331bc770",
    message = "This is a sample message",
    customMessageType = "file-message"
).async { result ->
    result.onFailure { exception ->
        // Handle error
    }.onSuccess { value ->
        // Handle successful method result
    }
}
```

### Response

```kotlin
[1, "Sent", "17483548017978763"]
```

### Returns

The sendFile() operation returns a `PNFileUploadResult` which contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `timetoken` | Long | The timetoken at which the message was published. |
| `status` | Int | Remote call return code. |
| `file` | PNBaseFile | Uploaded file information. |

`PNBaseFile` contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `id` | Long | Unique identifier of the uploaded file |
| `name` | String | Name of the uploaded file |