Sending images and files
The File Sharing feature allows users to upload and share files with other users in the application. You can upload videos, images, or documents of up to 5 MB in size. This feature is commonly used in social apps to share images or in medical apps to share medical records for patients.
When a file is uploaded on a channel, it's stored and managed on your key using a storage service. Subscribers of that channel receive a file message which contains a file ID, filename, and an optional description. You can use PubNub's SDKs to generate a URL to display the file or download the file directly.
You can use functions to integrate with third-party services (image moderation, for example) before file messages are shared with other users. When file messages are published, they can trigger functions of Before Publish File
and After Publish File
event types.
Send a file
Sending a file is a lot like publishing a message.
Use the sendFile
method and specify the channel on which to send the file and provide the actual file. You can also optionally include some text to use as a caption for the file. For more details on working with files, refer to File Sharing.
The following code sends a file cat_picture.jpg
to the channel my_channel
:
- JavaScript
- Java
- C#
- Objective-C
- Python
- Unity
- Swift
- Dart
1// in browser
2 const input = document.querySelector('input[file]');
3
4 input.addEventListener('change', async () => {
5 const file = input.files[0];
6
7 const result = await pubnub.sendFile({
8 channel: 'my_channel',
9 file: file,
10 });
11 });
12
13// in Node.js
14 import fs from 'fs';
15
show all 36 lines1pubnub.sendFile()
2 .channel("my_channel"
3 .fileName("cat_picture.jpg")
4 .inputStream(inputStream)
5 .cipherKey("my_cipher_key")
6 .message("Look at this photo!")
7 .async(result -> { /* check result */ });
1PNResult<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}
1NSURL *localFileURL = ...;
2PNSendFileRequest *request = [PNSendFileRequest requestWithChannel:@"channel"
3 fileURL:localFileURL];
4
5[self.client sendFileWithRequest:request completion:^(PNSendFileStatus *status) {
6 if (!status.isError) {
7 /**
8 * File upload successfully completed.
9 * Uploaded file information is available here:
10 * status.data.fileIdentifier is the unique file identifier
11 * status.data.fileName is the name used to store the file
12 */
13 } else {
14 /**
15 * Handle send file error. Check the 'category' property for reasons
show all 22 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 should_store(True).
8 ttl(222).
9 file_object(fd).
10 cipher_key("secret").sync()
11
12# multithreaded asynchronous
13def callback(response, status):
14 pass
15
show all 24 lines1pubnub.SendFile().
2 Channel("my_channel").
3 Message("Look at this photo!").
4 Name("cat_picture.jpg").
5 FilePath("cat_picture.jpg").
6 Async((result, status) => {
7 Debug.Log(result);
8 if(!status.Error){
9 Debug.Log("result.Data.ID:" + result.Data.ID);
10 Debug.Log("result.Timetoken:" + result.Timetoken);
11 }
12});
1pubnub.send(
2 .file(url: "cat_picture.jpg"),
3 channel: "my_channel",
4 remoteFilename: "cat_picture.jpg",
5 publishRequest: .init(additionalMessage: ["text": "Look at this photo!"])
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 // Initialize the PubNub instance with your configuration
6 var pubnub = PubNub(
7 defaultKeyset: Keyset(
8 subscribeKey: 'sub-c-abc-123', // Replace with your subscribe key
9 publishKey: 'pub-c-def-456' // Replace with your publish key
10 ),
11 );
12
13 // Read the file
14 var inputFile = File('cat_picture.jpg').readAsBytesSync();
15
show all 30 linesClients can add a File Listener to receive file events on their application and display the file in a browser or download the file.
Sample file event:
1{
2"channel":"demo-channel",
3"message": null,
4"subscription": null,
5"timetoken":"15958540412130227",
6"publisher":"javascript-fileUploadApiV1-tests-main",
7"file":{
8 "id":"t35t-f1l3-1d",
9 "name":"testFile.json",
10 "url":"example.com/v1/files/your-key/channels/demo-channel/files/t35t-f1l3-1d/testFile.json"
11 }
12}