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
// in browser
const input = document.querySelector('input[file]');
input.addEventListener('change', async () => {
const file = input.files[0];
const result = await pubnub.sendFile({
channel: 'my_channel',
file: file,
});
});
// in Node.js
import fs from 'fs';
show all 36 linespubnub.sendFile()
.channel("my_channel"
.fileName("cat_picture.jpg")
.inputStream(inputStream)
.cipherKey("my_cipher_key")
.message("Look at this photo!")
.async(result -> { /* check result */ });
PNResult<PNFileUploadResult> fileUploadResponse = await pubnub.SendFile()
.Channel("my_channel")
.File("cat_picture.jpg") // checks the bin folder if no path is provided
.Message("Look at this photo!")
.ExecuteAsync();
PNFileUploadResult fileUploadResult = fileUploadResponse.Result;
PNStatus fileUploadStatus = fileUploadResponse.Status; // contains troubleshooting info
if (!fileUploadStatus.Error && fileUploadResult != null) // checks if successful
{
Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(fileUploadResult));
}
else
{
Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(fileUploadStatus));
}
NSURL *localFileURL = ...;
PNSendFileRequest *request = [PNSendFileRequest requestWithChannel:@"channel"
fileURL:localFileURL];
[self.client sendFileWithRequest:request completion:^(PNSendFileStatus *status) {
if (!status.isError) {
/**
* File upload successfully completed.
* Uploaded file information is available here:
* status.data.fileIdentifier is the unique file identifier
* status.data.fileName is the name used to store the file
*/
} else {
/**
* Handle send file error. Check the 'category' property for reasons
show all 22 lines# synchronous
with open("cat_picture.jpg", "rb") as fd:
envelope = pubnub.send_file().
channel("my_channel").
file_name("cat_picture.jpg").
message({"test_message": "test"}).
should_store(True).
ttl(222).
file_object(fd).
cipher_key("secret").sync()
# multithreaded asynchronous
def callback(response, status):
pass
show all 24 linespubnub.SendFile().
Channel("my_channel").
Message("Look at this photo!").
Name("cat_picture.jpg").
FilePath("cat_picture.jpg").
Async((result, status) => {
Debug.Log(result);
if(!status.Error){
Debug.Log("result.Data.ID:" + result.Data.ID);
Debug.Log("result.Timetoken:" + result.Timetoken);
}
});
pubnub.send(
.file(url: "cat_picture.jpg"),
channel: "my_channel",
remoteFilename: "cat_picture.jpg",
publishRequest: .init(additionalMessage: ["text": "Look at this photo!"])
) { (fileTask) in
print("The task \(fileTask.urlSessionTask.taskIdentifier) has started uploading; 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, file, publishedAt)):
print("The file with an ID of \(file.fileId) was uploaded at \(publishedAt) timetoken) ")
case let .failure(error):
print("An error occurred while uploading the file: \(error.localizedDescription)")
show all 17 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:
{
"channel":"demo-channel",
"message": null,
"subscription": null,
"timetoken":"15958540412130227",
"publisher":"javascript-fileUploadApiV1-tests-main",
"file":{
"id":"t35t-f1l3-1d",
"name":"testFile.json",
"url":"example.com/v1/files/your-key/channels/demo-channel/files/t35t-f1l3-1d/testFile.json"
}
}