Receive and download files

Showing JavaScript examples.

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.

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

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.

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

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 lines

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.

Was this page useful?

Last updated on