Send a file to a channel
This guide shows you how to upload a file to a PubNub channel. When the upload completes, PubNub delivers a file event to all subscribers on that channel.
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, PHP 9.0.3, 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.
File size limit
| Function | Limit | Notes |
|---|---|---|
| File size | 5 MB | To raise it, contact support@pubnub.com. |
| File retention | File retention is 1 or 7 days on the Free plan, 30 days on Starter, and Unlimited on Pro. | Set it per keyset in the Admin Portal. |
| Files per list call | A single list-files call returns up to 100 files for a channel. |
Send a file
Choose the channel and the file. You can attach an optional text caption to the upload.
Custom message types
Not all SDKs support sending files with a custom message type. For details, see Message Types.
- JavaScript
- C#
- Go
- Objective-C
- Java
- Python
- PHP
- Swift
- Dart
The upload code differs by environment because each one selects or reads the file differently. 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
9const input = document.querySelector('input[type="file"]');
10
11input.addEventListener('change', async () => {
12 const file = input.files[0];
13 if (!file) {
14 console.error('No file selected.');
15 return;
show all 23 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
10const myFile = fs.createReadStream('./cat_picture.jpg');
11
12const result = await pubnub.sendFile({
13 channel: 'my_channel',
14 file: { stream: myFile, name: 'cat_picture.jpg', mimeType: 'image/jpeg' },
15 customMessageType: 'file-message',
show all 16 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// Local URI of the image to upload, for example returned by an image picker.
10const imageUri = 'file:///path/to/cat_picture.jpg';
11
12const result = await pubnub.sendFile({
13 channel: 'my_channel',
14 message: {
15 test: 'message',
show all 24 lines1PNResult<PNFileUploadResult> fileUploadResponse = await pubnub.SendFile()
2 .Channel("my_channel")
3 .File("cat_picture.jpg") // checks the bin folder if no path is provided
4 .Message("Look at this photo!")
5 .ExecuteAsync();
6PNFileUploadResult fileUploadResult = fileUploadResponse.Result;
7PNStatus fileUploadStatus = fileUploadResponse.Status; // contains troubleshooting info
8if (!fileUploadStatus.Error && fileUploadResult != null) // checks if successful
9{
10 Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(fileUploadResult));
11}
12else
13{
14 Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(fileUploadStatus));
15}
1file, err := os.Open("cat_picture.jpg")
2defer file.Close()
3if err != nil {
4 panic(err)
5}
6resSendFile, statusSendFile, errSendFile := pn.SendFile().
7 Channel("my_channel").
8 Message("Look at this photo!").
9 Name("cat_picture.jpg").
10 File(file).Execute()
11fmt.Println(resSendFile, statusSendFile, errSendFile)
12fmt.Println(resSendFile.Data.ID)
1NSURL *localFileURL = ...;
2PNSendFileRequest *request = [PNSendFileRequest requestWithChannel:@"my_channel"
3 fileURL:localFileURL];
4request.customMessageType = @"file-message";
5
6[self.client sendFileWithRequest:request completion:^(PNSendFileStatus *status) {
7 if (!status.isError) {
8 /**
9 * File upload successfully completed.
10 * Uploaded file information is available here:
11 * status.data.fileIdentifier is the unique file identifier
12 * status.data.fileName is the name used to store the file
13 */
14 } else {
15 /**
show all 23 lines1pubnub.sendFile()
2 .channel("my_channel")
3 .fileName("cat_picture.jpg")
4 .customMessageType("file-message")
5 .inputStream(inputStream)
6 .message("Look at this photo!")
7 .async(result -> {
8 result.onSuccess(res -> {
9 System.out.println("send timetoken: " + res.getTimetoken());
10 System.out.println("send status: " + res.getStatus());
11 System.out.println("send fileId: " + res.getFile().getId());
12 System.out.println("send fileName: " + res.getFile().getName());
13 }).onFailure(exception -> {
14 exception.printStackTrace();
15 });
show all 16 lines1# synchronous
2with open("cat_picture.jpg", "rb") as fd:
3 envelope = pubnub.send_file() \
4 .channel("my_channel") \
5 .file_name("cat_picture.jpg") \
6 .message({"test_message": "test"}) \
7 .custom_message_type('file-message') \
8 .should_store(True) \
9 .ttl(222) \
10 .file_object(fd) \
11 .cipher_key("secret") \
12 .sync()
13
14# multithreaded asynchronous
15def callback(result, status):
show all 31 lines1
1pubnub.send(
2 .file(url: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("cat_picture.jpg")),
3 channel: "my_channel",
4 remoteFilename: "cat_picture.jpg",
5 publishRequest: .init(additionalMessage: ["text": "Look at this photo!"], customMessageType: "file-message")
6) { (fileTask) in
7 print("The task \(fileTask.urlSessionTask.taskIdentifier) has started uploading; no need to call `resume()`")
8 print("If needed, the `URLSessionUploadTask` can be accessed with `fileTask.urlSessionTask`")
9 print("You can use `fileTask.progress` to populate a `UIProgressView`/`ProgressView` ")
10} completion: { (result) in
11 switch result {
12 case let .success((task, file, publishedAt)):
13 print("The file with an ID of \(file.fileId) was uploaded at \(publishedAt) timetoken) ")
14 case let .failure(error):
15 print("An error occurred while uploading the file: \(error.localizedDescription)")
show all 17 lines1import '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 var inputFile = File('cat_picture.jpg').readAsBytesSync();
13
14 try {
15 var result = await pubnub.files.sendFile(
show all 27 linesA successful upload returns a timetoken. Subscribers on the channel receive a file event carrying the file ID, file name, and a download URL. For how to handle that event on the subscriber side, see Receive and download files.
Encrypt a file
To encrypt a file before upload, set a cipher key in the SDK client configuration or pass it per upload request. Any client that downloads the file must use the same key. For how encryption works, see Files.
The Python example above shows cipher_key("secret") as an inline parameter. Check your SDK's configuration reference for the client-level cipher key option.
Related tasks
- Receive and download files. Handle the file event on the subscriber side and build a download URL.
- List and manage stored files. List files in a channel and delete uploads.