---
source_url: https://www.pubnub.com/docs/sdks/go/api-reference/files
title: File Sharing API for Go SDK
updated_at: 2026-06-19T11:37:23.936Z
sdk_name: PubNub Go SDK
sdk_version: v9.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 Go SDK

PubNub Go SDK, use the latest version: v9.0.1

Install:

```bash
go get github.com/pubnub/go/v9@v9.0.1
```

Use the Files API to upload and share files up to 5 MB on PubNub. 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, `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)

```go
pn.SendFile().
    Channel(string).
    Message(interface{}).
    Name(string).
    File(*os.File).
    TTL(int).
    ShouldStore(bool).
    Meta(interface{}).
    CustomMessageType(string).
    UseRawMessage(bool).    
    Execute()
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| Channel | string | Yes |  | Channel to upload the file. |
| Message | interface | Optional |  | Message to send along with the file to the specified `channel`. Accepts any JSON-serializable type: `string`, `map[string]interface{}`, `[]interface{}`, `number`, `bool`, etc. |
| File | *os.File | Yes |  | Pointer to the file object. |
| TTL | int | Optional |  | How long the message should be stored in the channel's storage. |
| ShouldStore | bool | Optional | `false` | Whether to store the published file message in the channel's history. |
| Meta | interface | Optional | `null` | Metadata object which can be used with the filtering ability. |
| 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`. |
| UseRawMessage | bool | Optional | `false` | When `true`, the message is sent directly without the `{"text": ...}` wrapper. When `false` (default), the message is wrapped in a `"text"` field for backward compatibility. Works with any JSON-serializable type: `string`, `map[string]interface{}`, `[]interface{}`, `number`, `bool`, etc. |

:::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/go/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.
:::

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"
	"os"

	pubnub "github.com/pubnub/go/v9"
)

// Example_sendFile demonstrates uploading a file to a channel
func Example_sendFile() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo" // Replace with your subscribe key
	config.PublishKey = "demo"   // Replace with your publish key

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	pn := pubnub.NewPubNub(config)

	// snippet.hide
	// Create a test file for testing
	testFile, _ := os.CreateTemp("", "test_*.txt")
	testFile.WriteString("Hello, this is a test file!")
	testFile.Close()
	defer os.Remove(testFile.Name())
	// snippet.show

	// Open the file you want to upload
	file, err := os.Open(
		testFile.Name(), // Replace with testFile.Name() with your file path
	)
	if err != nil {
		fmt.Printf("Error opening file: %v\n", err)
		return
	}
	defer file.Close()

	// Upload file to channel
	response, status, err := pn.SendFile().
		Channel("my-channel").
		Name("my_text_file.txt").        // Name of the file
		File(file).                      // File to upload
		Message("Check out this file!"). // Optional message
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	// snippet.hide
	// Cleanup uploaded file
	if response != nil && response.Data.ID != "" {
		pn.DeleteFile().
			Channel("my-channel").
			ID(response.Data.ID).
			Name("my_text_file.txt").
			Execute()
	}
	// snippet.show

	if status.StatusCode == 200 && response.Data.ID != "" {
		fmt.Println("File uploaded successfully")
	}

	// Output:
	// File uploaded successfully
}
```

### Returns

The `SendFile()` operation returns a type `PNSendFileResponse` which contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `Data` | PNFileData | Details of type `PNFileData` are [here](#pnfiledata) |
| `Timestamp` | int64 | Returns an `int64` representation of the timetoken when the message was published. |

#### PNFileData

`PNFileData` contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `ID` | string | Returns the `ID` of the 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.
:::

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

response, status, err := pn.SendFile().
  Channel("my-channel").
  Message(message).
  File(file).
  Name("example.txt").
  UseRawMessage(true).
  Execute()
```

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)

```go
pn.ListFiles().
    Channel(string).
    Limit(int).
    Next(string).
    Execute()
```

| Parameter | Description |
| --- | --- |
| `Channel` *Type: stringDefault: n/a | `Channel` to get list of files. |
| `Limit`Type: intDefault: 100 | Number of files to return. |
| `Next`Type: stringDefault: 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

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"
	"os"

	pubnub "github.com/pubnub/go/v9"
)

// Example_listFiles demonstrates listing all files in a channel
func Example_listFiles() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	pn := pubnub.NewPubNub(config)

	// List all files in the channel
	response, status, err := pn.ListFiles().
		Channel("files-channel").
		Limit(25). // Limit number of results
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 {
		fmt.Printf("Found %d file(s) in channel\n", len(response.Data))
	}
}
```

### Returns

The `ListFiles()` operation returns a type `PNListFilesResponse` which contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `Data` | PNFileInfo | Details of type PNFileData are [here](#pnfileinfo) |
| `Count` | int | Number of files returned. |
| `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. |

#### PNFileInfo

`PNFileInfo` contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `Name` | string | Name of the file. |
| `Id` | string | ID of the file. |
| `Size` | int | `Size` of the file. |
| `Created` | string | `Created` date of the file. |

## Get file URL

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

### Method(s)

```go
pn.GetFileURL().
    Channel(string).
    ID(string).
    Name(string).
    Execute()
```

| Parameter | Description |
| --- | --- |
| `Channel` *Type: string | Name of `channel` within which `file` with `name` has been uploaded. |
| `ID` *Type: string | Unique file `identifier` which has been assigned during file upload. |
| `Name` *Type: string | Name under which the uploaded `file` is stored for the `channel`. |

### Sample code

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"
	"os"

	pubnub "github.com/pubnub/go/v9"
)

// Example_getFileURL demonstrates generating a download URL for a file
func Example_getFileURL() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	pn := pubnub.NewPubNub(config)

	// snippet.hide
	// Upload a test file first for testing
	testFile, _ := os.CreateTemp("", "test_*.txt")
	testFile.WriteString("Test file for URL generation")
	testFile.Close()
	defer os.Remove(testFile.Name())

	file, _ := os.Open(testFile.Name())
	uploadResp, _, _ := pn.SendFile().
		Channel("files-channel").
		Name("sample.txt").
		File(file).
		Execute()
	file.Close()

	if uploadResp == nil || uploadResp.Data.ID == "" {
		return
	}
	// snippet.show

	// Get the download URL for a specific file
	// You would get these values from your file upload response or ListFiles
	fileID := uploadResp.Data.ID // Replace uploadResp.Data.ID with your file ID
	fileName := "sample.txt"     // Replace with your file name

	// snippet.hide
	defer pn.DeleteFile().
		Channel("files-channel").
		ID(fileID).
		Name(fileName).
		Execute()
	// snippet.show

	response, status, err := pn.GetFileURL().
		Channel("files-channel").
		ID(fileID).     // File ID from upload response
		Name(fileName). // File name from upload response
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 && response.URL != "" {
		fmt.Println("File URL generated successfully")
	}

	// Output:
	// File URL generated successfully
}
```

### Returns

The `GetFileUrl()` operation returns a type `PNGetFileURLResponse` which contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `Url` | string | `URL` which can be used to download remote file with specified `name` and `identifier`. |

## Download file

Download a file from the specified `channel`.

### Method(s)

```go
pn.DownloadFile().
    Channel(string).
    ID(string).
    Name(string).
    Execute()
```

| Parameter | Description |
| --- | --- |
| `Channel` *Type: string | Name of `channel` within which `file` with `name` has been uploaded. |
| `ID` *Type: string | Unique `file` identifier which has been assigned during `file` upload. |
| `Name` *Type: string | Name under which uploaded `file` is stored for `channel`. |

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

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"
	"os"

	pubnub "github.com/pubnub/go/v9"
)

// Example_downloadFile demonstrates downloading a file from a channel
func Example_downloadFile() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	pn := pubnub.NewPubNub(config)

	// snippet.hide
	// Upload a test file first for testing
	testFile, _ := os.CreateTemp("", "test_*.txt")
	testFile.WriteString("Test file for download")
	testFile.Close()
	defer os.Remove(testFile.Name())

	file, _ := os.Open(testFile.Name())
	uploadResp, _, _ := pn.SendFile().
		Channel("files-channel").
		Name("download.txt").
		File(file).
		Execute()
	file.Close()

	if uploadResp == nil || uploadResp.Data.ID == "" {
		return
	}
	// snippet.show

	// Download a specific file
	// You would get these values from your file upload response or ListFiles
	fileID := uploadResp.Data.ID // Replace uploadResp.Data.ID with your file ID
	fileName := "download.txt"   // Replace with your file name

	// snippet.hide
	defer pn.DeleteFile().
		Channel("files-channel").
		ID(fileID).
		Name(fileName).
		Execute()
	// snippet.show

	_, status, err := pn.DownloadFile().
		Channel("files-channel").
		ID(fileID).     // File ID from upload or list response
		Name(fileName). // File name
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 {
		fmt.Println("File downloaded successfully")
	}

	// Output:
	// File downloaded successfully
}
```

### Returns

The `DownloadFile()` operation returns a type `PNDownloadFileResponse` which contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `File` | `io.Reader` | File Reader that can be used to save the `File`. |

## Delete file

Delete a file from the specified `channel`.

### Method(s)

```go
pn.DeleteFile().
    Channel(string).
    ID(string).
    Name(string).
    Execute()
```

| Parameter | Description |
| --- | --- |
| `Channel` *Type: string | Name of `channel` within which `file` with `name` needs to be deleted. |
| `ID` *Type: string | Unique `file` identifier of the `file` to be deleted. |
| `Name` *Type: string | Name of the `file` to be deleted from the `channel`. |

### Sample code

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"
	"os"

	pubnub "github.com/pubnub/go/v9"
)

// Example_deleteFile demonstrates deleting a file from a channel
func Example_deleteFile() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	pn := pubnub.NewPubNub(config)

	// snippet.hide
	// Upload a test file first for testing
	testFile, _ := os.CreateTemp("", "test_*.txt")
	testFile.WriteString("Test file for deletion")
	testFile.Close()
	defer os.Remove(testFile.Name())

	file, _ := os.Open(testFile.Name())
	uploadResp, _, _ := pn.SendFile().
		Channel("files-channel").
		Name("to-delete.txt").
		File(file).
		Execute()
	file.Close()

	if uploadResp == nil || uploadResp.Data.ID == "" {
		return
	}
	// snippet.show

	// Delete a specific file
	// You would get these values from your file upload response or ListFiles
	fileID := uploadResp.Data.ID // Replace uploadResp.Data.ID with your file ID
	fileName := "to-delete.txt"  // Replace with your file name

	_, status, err := pn.DeleteFile().
		Channel("files-channel").
		ID(fileID).     // File ID from upload or list response
		Name(fileName). // File name
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 {
		fmt.Println("File deleted successfully")
	}

	// Output:
	// File deleted successfully
}
```

### Returns

The `DeleteFile()` operation returns a type `PNDeleteFileResponse` which is `nil`.

## 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)

```go
pn.PublishFileMessage().
    TTL(int).
    Meta(interface{}).
    ShouldStore(bool).
    Channel(string).
    Message(PNPublishFileMessage).
    CustomMessageType(string).
    UseRawMessage(bool).
    Execute()
```

| Parameter | Description |
| --- | --- |
| `TTL`Type: intDefault: n/a | How long message should be stored in channel's storage. |
| `Meta`Type: interfaceDefault: n/a | Meta data object which can be used with the filtering ability. |
| `ShouldStore`Type: boolDefault: `true` | Store in `history`. |
| `Channel` *Type: stringDefault: n/a | Name of `channel` to publish file message. |
| `Message` *Type: PNPublishFileMessageDefault: n/a | The payload should be of the type `PNPublishFileMessage`. |
| `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`. |
| `UseRawMessage`Type: boolDefault: `false` | When `true`, the message is sent directly without the `{"text": ...}` wrapper. When `false` (default), the message is wrapped in a `"text"` field for backward compatibility. Works with any JSON-serializable type: `string`, `map[string]interface{}`, `[]interface{}`, `number`, `bool`, etc. |

### Sample code

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"
	"os"

	pubnub "github.com/pubnub/go/v9"
)

// Example_publishFileMessage demonstrates publishing a file message for an already uploaded file
func Example_publishFileMessage() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	pn := pubnub.NewPubNub(config)

	// Create the message payload
	messagePayload := &pubnub.PNPublishMessage{
		Text: "Check out this updated file!",
	}

	// Create the file info
	fileInfo := &pubnub.PNFileInfoForPublish{
		ID:   "d9515cb7-48a7-41a4-9284-f4bf331bc770", // File ID from previous upload
		Name: "cat_picture.jpg",                      // File name from previous upload
	}

	// Combine into file message
	fileMessage := pubnub.PNPublishFileMessage{
		PNFile:    fileInfo,
		PNMessage: messagePayload,
	}

	// Publish the file message
	response, status, err := pn.PublishFileMessage().
		Channel("files-publish-channel").
		Message(fileMessage).
		ShouldStore(true). // Store in history
		TTL(24).           // Message expires after 24 hours
		CustomMessageType("file_message").
		Meta(map[string]interface{}{
			"file_type": "image",
			"file_size": 1024,
			"file_name": "cat_picture.jpg",
		}).
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 && response.Timestamp > 0 {
		fmt.Println("File message published successfully")
	}
}
```

### Returns

The `PublishFileMessage()` operation returns type `PublishFileMessageResponse` which contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `Timetoken` | int64 | Returns a long representation of the timetoken when the `message` was published. |