Receive and download files
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. For how the feature works, see Files.
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.
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
- C#
- Go
- Objective-C
- Java
- Python
- Swift
- Dart
1const result = pubnub.getFileUrl({ channel: 'my_channel', id: 'd9515cb7-48a7-41a4-9284-f4bf331bc770', name: 'cat_picture.jpg' });
1PNResult<PNFileUrlResult> getFileUrlResponse = await pubnub.GetFileUrl()
2 .Channel("my_channel")
3 .FileId("d9515cb7-48a7-41a4-9284-f4bf331bc770")
4 .FileName("cat_picture.jpg")
5 .ExecuteAsync();
6PNFileUrlResult getFileUrlResult = getFileUrlResponse.Result;
7PNStatus getFileUrlStatus = getFileUrlResponse.Status;
8if (getFileUrlResult != null)
9{
10 Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(getFileUrlResult));
11}
12else
13{
14 Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(getFileUrlStatus));
15}
1resGetFile, statusGetFile, errGetFile := pn.GetFileURL().
2 Channel("my_channel").
3 ID("d9515cb7-48a7-41a4-9284-f4bf331bc770").
4 Name("cat_picture.jpg").Execute()
5fmt.Println(resGetFile, statusGetFile, errGetFile)
6fmt.Println(resGetFile.URL)
1NSURL *url = [self.client downloadURLForFileWithName:@"cat_picture.jpg"
2 identifier:@"<file-identifier>"
3 inChannel:@"my_channel"];
1pubnub.getFileUrl()
2 .channel("my_channel")
3 .fileName("cat_picture.jpg")
4 .fileId("d9515cb7-48a7-41a4-9284-f4bf331bc770")
5 .async(result -> {
6 result.onSuccess(res -> {
7 System.out.println("getUrl fileUrl: " + res.getUrl());
8 }).onFailure(exception -> {
9 exception.printStackTrace();
10 });
11 });
1# Synchronous:
2envelope = pubnub.get_file_url() \
3 .channel("my_channel") \
4 .file_id("fileID") \
5 .file_name("cat_picture.jpg") \
6 .sync()
7
8
9# Multithreaded asynchronous:
10def callback(result, status):
11 if status.is_error():
12 print(f"Request failed: {status.error_data}")
13 return
14 print(result)
15
show all 20 lines1
1import 'package:pubnub/pubnub.dart';
2
3void main() async {
4 var pubnub = PubNub(
5 defaultKeyset: Keyset(
6 subscribeKey: 'sub-c-abc-123', // Replace with your subscribe key
7 publishKey: 'pub-c-def-456' // Replace with your publish key
8 ),
9 );
10
11 var fileUrl = pubnub.files.getFileUrl(
12 'my_channel',
13 'd9515cb7-48a7-41a4-9284-f4bf331bc770',
14 'cat_picture.jpg'
15 );
show all 18 linesThe 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
- C#
- Go
- Objective-C
- Java
- Python
- Swift
- Dart
The download code differs by environment because each one hands the file content to a different destination. Choose the tab for your environment.
- Web
- Node.js
- React Native
1import PubNub from 'pubnub';
2
3const pubnub = new PubNub({
4 publishKey: 'YOUR_PUBLISH_KEY',
5 subscribeKey: 'YOUR_SUBSCRIBE_KEY',
6 userId: 'YOUR_USER_ID',
7});
8
9// Use the file ID and name from the file event.
10const file = await pubnub.downloadFile({
11 channel: 'my_channel',
12 id: 'd9515cb7-48a7-41a4-9284-f4bf331bc770',
13 name: 'cat_picture.jpg',
14});
15
show all 19 lines1import fs from 'fs';
2import PubNub from 'pubnub';
3
4const pubnub = new PubNub({
5 publishKey: 'YOUR_PUBLISH_KEY',
6 subscribeKey: 'YOUR_SUBSCRIBE_KEY',
7 userId: 'YOUR_USER_ID',
8});
9
10// Use the file ID and name from the file event.
11const file = await pubnub.downloadFile({
12 channel: 'my_channel',
13 id: 'd9515cb7-48a7-41a4-9284-f4bf331bc770',
14 name: 'cat_picture.jpg',
15});
show all 24 lines1import PubNub from 'pubnub';
2
3const pubnub = new PubNub({
4 publishKey: 'YOUR_PUBLISH_KEY',
5 subscribeKey: 'YOUR_SUBSCRIBE_KEY',
6 userId: 'YOUR_USER_ID',
7});
8
9// Use the file ID and name from the file event.
10const file = await pubnub.downloadFile({
11 channel: 'my_channel',
12 id: 'd9515cb7-48a7-41a4-9284-f4bf331bc770',
13 name: 'cat_picture.jpg',
14});
15
show all 16 lines1PNResult<PNDownloadFileResult> fileDownloadResponse = await pubnub.DownloadFile()
2 .Channel("my_channel")
3 .FileId("d9515cb7-48a7-41a4-9284-f4bf331bc770")
4 .FileName("cat_picture.jpg")
5 .ExecuteAsync();
6PNDownloadFileResult fileDownloadResult = fileDownloadResponse.Result;
7PNStatus fileDownloadStatus = fileDownloadResponse.Status;
8if (fileDownloadResult != null)
9{
10 fileDownloadResult.SaveFileToLocal(downloadUrlFileName); // saves to bin folder if no path is provided
11 Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(fileDownloadResult.FileName));
12}
13else
14{
15 Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(fileDownloadStatus));
show all 16 lines1resDLFile, statusDLFile, errDLFile := pn.DownloadFile().
2 Channel("my_channel").
3 ID("d9515cb7-48a7-41a4-9284-f4bf331bc770").
4 Name("cat_picture.jpg").Execute()
5if resDLFile != nil {
6 filepathOutput := "cat_picture.jpg"
7 out, _ := os.Create(filepathOutput)
8 _, err := io.Copy(out, resDLFile.File)
9
10 if err != nil {
11 fmt.Println(err)
12 }
13}
1PNDownloadFileRequest *request = [PNDownloadFileRequest requestWithChannel:@"my_channel"
2 identifier:@"<file-identifier>"
3 name:@"cat_picture.jpg"];
4request.targetURL = ...;
5
6[self.client downloadFileWithRequest:request
7 completion:^(PNDownloadFileResult *result, PNErrorStatus *status) {
8 if (!status.isError) {
9 /**
10 * File successfully has been downloaded.
11 * status.data.location - location where downloaded file can be found
12 * status.data.temporary - whether file has been downloaded to temporary storage and
13 * will be removed on completion block return.
14 */
15 } else {
show all 23 lines1pubnub.downloadFile()
2 .channel("my_channel")
3 .fileName("cat_picture.jpg")
4 .fileId("d9515cb7-48a7-41a4-9284-f4bf331bc770")
5 .async(result -> {
6 result.onSuccess(res -> {
7 System.out.println("getFile fileName: " + res.getFileName());
8 System.out.println("getFile byteStream: " + res.getByteStream());
9 }).onFailure(exception -> {
10 exception.printStackTrace();
11 });
12 });
1# synchronous:
2download_envelope = pubnub.download_file() \
3 .channel("my_channel") \
4 .file_id("fileId") \
5 .file_name("cat_picture.jpg") \
6 .sync()
7
8# Multithreaded asynchronous:
9def callback(result, status):
10 if status.is_error():
11 print(f"Request failed: {status.error_data}")
12 return
13 print(result)
14
15pubnub.download_file() \
show all 19 lines1
1import 'dart:io';
2import 'package:pubnub/pubnub.dart';
3
4void main() async {
5 var pubnub = PubNub(
6 defaultKeyset: Keyset(
7 subscribeKey: 'sub-c-abc-123', // Replace with your subscribe key
8 publishKey: 'pub-c-def-456' // Replace with your publish key
9 ),
10 );
11
12 try {
13 var result = await pubnub.files.downloadFile(
14 'my_channel',
15 'd9515cb7-48a7-41a4-9284-f4bf331bc770',
show all 25 linesEncrypted 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.
Related tasks
- Send a file to a channel. Upload a file and attach an optional text caption.
- List and manage stored files. List files in a channel and delete uploads.