---
source_url: https://www.pubnub.com/docs/data-storage/files/receive-and-download-files
title: Receive and download files
updated_at: 2026-09-30T07:20:08.000Z
---

# Receive and download files

## Documentation index

To discover more PubNub resources:

1. Fetch [PubNub's llms.txt](https://www.pubnub.com/llms-full.txt) for a list of available pages in Markdown format.
2. Identify relevant URLs from that index.
3. Fetch the target pages.

Do not assume a path exists, always check the index first.

This guide shows you how to receive a file event on a subscribed channel and download the file. A file event carries the file ID and file name but no URL. You build the URL using an SDK method before downloading.

The examples on this page are written for the current SDK releases: C# 9.0.0, Dart 8.0.3, Go v10.0.0, Java 6.4.5, JavaScript 13.0.3 (web, Node.js, and React Native tabs), Objective-C 7.0.4, Python 10.7.2, and Swift 10.2.0. Each example assumes a PubNub client initialized for its SDK, unless the example sets one up itself.

**Prerequisite:** File Sharing must be enabled on your keyset in the [Admin Portal](https://admin.pubnub.com). For how the feature works, see [Files](https://www.pubnub.com/docs/data-storage/files/overview.md).

## Receive a file event

Subscribe to the channel and listen for file events on your existing message listener. No separate subscription is required. File events arrive with message type `4` alongside regular messages. For how to set up a channel listener, see [Receive messages](https://www.pubnub.com/docs/pub-sub/subscribe/receive-messages.md).

## Get the download URL

A file event contains the file ID and file name. Use the `getFileUrl` SDK method to build a URL for viewing or downloading the file.

### JavaScript

```javascript
const result = pubnub.getFileUrl({ channel: 'my_channel', id: 'd9515cb7-48a7-41a4-9284-f4bf331bc770', name: 'cat_picture.jpg' });
```

### C#

```csharp
PNResult<PNFileUrlResult> getFileUrlResponse = await pubnub.GetFileUrl()
    .Channel("my_channel")
    .FileId("d9515cb7-48a7-41a4-9284-f4bf331bc770")
    .FileName("cat_picture.jpg")
    .ExecuteAsync();
PNFileUrlResult getFileUrlResult = getFileUrlResponse.Result;
PNStatus getFileUrlStatus = getFileUrlResponse.Status;
if (getFileUrlResult != null)
{
    Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(getFileUrlResult));
}
else
{
    Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(getFileUrlStatus));
}
```

### Go

```go
resGetFile, statusGetFile, errGetFile := pn.GetFileURL().
  Channel("my_channel").
  ID("d9515cb7-48a7-41a4-9284-f4bf331bc770").
  Name("cat_picture.jpg").Execute()
fmt.Println(resGetFile, statusGetFile, errGetFile)
fmt.Println(resGetFile.URL)
```

### Objective-C

```objectivec
NSURL *url = [self.client downloadURLForFileWithName:@"cat_picture.jpg"
                                          identifier:@"<file-identifier>"
                                           inChannel:@"my_channel"];
```

### Java

```java
pubnub.getFileUrl()
        .channel("my_channel")
        .fileName("cat_picture.jpg")
        .fileId("d9515cb7-48a7-41a4-9284-f4bf331bc770")
        .async(result -> {
            result.onSuccess(res -> {
                System.out.println("getUrl fileUrl: " + res.getUrl());
            }).onFailure(exception -> {
                exception.printStackTrace();
            });
        });
```

### Python

```python
# Synchronous:
envelope = pubnub.get_file_url() \
    .channel("my_channel") \
    .file_id("fileID") \
    .file_name("cat_picture.jpg") \
    .sync()

# Multithreaded asynchronous:
def callback(result, status):
    if status.is_error():
        print(f"Request failed: {status.error_data}")
        return
    print(result)

pubnub.get_file_url() \
    .channel("my_channel") \
    .file_id("fileID") \
    .file_name("cat_picture.jpg") \
    .pn_async(callback)
```

### Swift

```swift
// Generate a download URL for a File
let downloadURL = try? pubnub.generateFileDownloadURL(
  channel: "some-channel",
  fileId: "some-file-id",
  filename: "filename"
)
```

### Dart

```dart
import 'package:pubnub/pubnub.dart';

void main() async {
  var pubnub = PubNub(
    defaultKeyset: Keyset(
      subscribeKey: 'sub-c-abc-123',  // Replace with your subscribe key
      publishKey: 'pub-c-def-456'     // Replace with your publish key
    ),
  );

  var fileUrl = pubnub.files.getFileUrl(
    'my_channel',
    'd9515cb7-48a7-41a4-9284-f4bf331bc770',
    'cat_picture.jpg'
  );

  print('File URL: $fileUrl');
}
```

The call returns a file URL. Use it to display the file in a browser or pass it to a download method.

## Download a file

Use the file ID and name from the event to download the file content directly.

### JavaScript

The download code differs by environment because each one hands the file content to a different destination. Choose the tab for your environment.

#### Web

```javascript
import PubNub from 'pubnub';

const pubnub = new PubNub({
  publishKey: 'YOUR_PUBLISH_KEY',
  subscribeKey: 'YOUR_SUBSCRIBE_KEY',
  userId: 'YOUR_USER_ID',
});

// Use the file ID and name from the file event.
const file = await pubnub.downloadFile({
  channel: 'my_channel',
  id: 'd9515cb7-48a7-41a4-9284-f4bf331bc770',
  name: 'cat_picture.jpg',
});

const myImageTag = document.createElement('img');
myImageTag.src = URL.createObjectURL(await file.toFile());

document.body.appendChild(myImageTag);
```

#### Node.js

```javascript
import fs from 'fs';
import PubNub from 'pubnub';

const pubnub = new PubNub({
  publishKey: 'YOUR_PUBLISH_KEY',
  subscribeKey: 'YOUR_SUBSCRIBE_KEY',
  userId: 'YOUR_USER_ID',
});

// Use the file ID and name from the file event.
const file = await pubnub.downloadFile({
  channel: 'my_channel',
  id: 'd9515cb7-48a7-41a4-9284-f4bf331bc770',
  name: 'cat_picture.jpg',
});

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

fileStream.pipe(output);

output.once('finish', () => {
  console.log('File saved to ./cat_picture.jpg');
});
```

#### React Native

```javascript
import PubNub from 'pubnub';

const pubnub = new PubNub({
  publishKey: 'YOUR_PUBLISH_KEY',
  subscribeKey: 'YOUR_SUBSCRIBE_KEY',
  userId: 'YOUR_USER_ID',
});

// Use the file ID and name from the file event.
const file = await pubnub.downloadFile({
  channel: 'my_channel',
  id: 'd9515cb7-48a7-41a4-9284-f4bf331bc770',
  name: 'cat_picture.jpg',
});

const fileContent = await file.toBlob();
```

### C#

```csharp
PNResult<PNDownloadFileResult> fileDownloadResponse = await pubnub.DownloadFile()
    .Channel("my_channel")
    .FileId("d9515cb7-48a7-41a4-9284-f4bf331bc770")
    .FileName("cat_picture.jpg")
    .ExecuteAsync();
PNDownloadFileResult fileDownloadResult = fileDownloadResponse.Result;
PNStatus fileDownloadStatus = fileDownloadResponse.Status;
if (fileDownloadResult != null)
{
    fileDownloadResult.SaveFileToLocal(downloadUrlFileName); // saves to bin folder if no path is provided
    Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(fileDownloadResult.FileName));
}
else
{
    Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(fileDownloadStatus));
}
```

### Go

```go
resDLFile, statusDLFile, errDLFile := pn.DownloadFile().
  Channel("my_channel").
  ID("d9515cb7-48a7-41a4-9284-f4bf331bc770").
  Name("cat_picture.jpg").Execute()
if resDLFile != nil {
    filepathOutput := "cat_picture.jpg"
    out, _ := os.Create(filepathOutput)
    _, err := io.Copy(out, resDLFile.File)

    if err != nil {
        fmt.Println(err)
    }
}
```

### Objective-C

```objectivec
PNDownloadFileRequest *request = [PNDownloadFileRequest requestWithChannel:@"my_channel"
                                                                identifier:@"<file-identifier>"
                                                                      name:@"cat_picture.jpg"];
request.targetURL = ...;

[self.client downloadFileWithRequest:request
                          completion:^(PNDownloadFileResult *result, PNErrorStatus *status) {
    if (!status.isError) {
        /**
         * File successfully has been downloaded.
         *   status.data.location - location where downloaded file can be found
         *   status.data.temporary - whether file has been downloaded to temporary storage and
         *                           will be removed on completion block return.
         */
    } else {
        /**
         * Handle file download error. Check 'category' property to find out possible issue
         * because of which request did fail.
         *
         * Request can be resent using: [status retry]
         */
    }
}];
```

### Java

```java
pubnub.downloadFile()
    .channel("my_channel")
    .fileName("cat_picture.jpg")
    .fileId("d9515cb7-48a7-41a4-9284-f4bf331bc770")
    .async(result -> {
        result.onSuccess(res -> {
            System.out.println("getFile fileName: " + res.getFileName());
            System.out.println("getFile byteStream: " + res.getByteStream());
        }).onFailure(exception -> {
            exception.printStackTrace();
        });
    });
```

### Python

```python
# synchronous:
download_envelope = pubnub.download_file() \
    .channel("my_channel") \
    .file_id("fileId") \
    .file_name("cat_picture.jpg") \
    .sync()

# Multithreaded asynchronous:
def callback(result, status):
    if status.is_error():
        print(f"Request failed: {status.error_data}")
        return
    print(result)

pubnub.download_file() \
    .channel("my_channel") \
    .file_id("fileID") \
    .file_name("cat_picture.jpg") \
    .pn_async(callback)
```

### Swift

```swift
// Replace `fileURL:` with your destination URL
let requestFile = PubNubLocalFileBase(
  channel: "my_channel",
  fileId: "fileId-from-PubNub",
  fileURL: URL(fileURLWithPath: "your/download/url.png")
)

// Download the File to the specified URL
pubnub.download(
  file: requestFile,
  toFileURL: requestFile.fileURL
) { (fileTask: HTTPFileDownloadTask) in
  print("The task \(fileTask.taskIdentifier) has started downloading; no need to call `resume()`")
  print("If needed, the `URLSessionUploadTask` can be accessed with `fileTask.urlSessionTask`")
  print("You can use `fileTask.progress` to populate a `UIProgressView`/`ProgressView`")
} completion: { result in
  switch result {
  case let .success((task, newFile)):
    print("The file task \(task.taskIdentifier) downloaded successfully to \(newFile.fileURL), which might be different than \(requestFile.fileURL)")
    print("This also might mean that \(newFile.filename) could be different from \(newFile.remoteFilename)")
  case let .failure(error):
    print("An error occurred while downloading the file: \(error.localizedDescription)")
  }
}
```

### Dart

```dart
import 'dart:io';
import 'package:pubnub/pubnub.dart';

void main() async {
  var pubnub = PubNub(
    defaultKeyset: Keyset(
      subscribeKey: 'sub-c-abc-123',  // Replace with your subscribe key
      publishKey: 'pub-c-def-456'     // Replace with your publish key
    ),
  );

  try {
    var result = await pubnub.files.downloadFile(
      'my_channel',
      'd9515cb7-48a7-41a4-9284-f4bf331bc770',
      'cat_picture.jpg'
    );

    await File('downloaded_cat_picture.jpg').writeAsBytes(result.fileContent);
    print('File downloaded successfully.');

  } catch (e) {
    print('Failed to download file: $e');
  }
}
```

## Encrypted files

If the file was uploaded with a cipher key, set the same key in your SDK client configuration before downloading. The SDK decrypts the content automatically. For how encryption works, see [Files](https://www.pubnub.com/docs/data-storage/files/overview.md#encryption).

## Related tasks

* [Send a file to a channel](https://www.pubnub.com/docs/data-storage/files/send-file-to-channel.md). Upload a file and attach an optional text caption.
* [List and manage stored files](https://www.pubnub.com/docs/data-storage/files/list-and-manage-stored-files.md). List files in a channel and delete uploads.

Last updated at: 2026-09-30T07:20:08.000Z
