PubNub Logo Docs
Support Contact Sales Login Try Our APIs

›MESSAGES

Collapse all
Dark mode

Back to Home

Overview

  • In-App Chat

Chat Components

  • Overview
  • REACT

    • React Components

    ANDROID

    • Getting Started
    • UI Components
    • Data Components
    • Chat Provider

    IOS

    • Getting Started
    • UI Components
    • Data Components
    • Chat Provider

SDKs

  • Overview
  • USERS

    • Setup
    • Metadata
    • Permissions
    • Presence
    • Mentions

    CHANNELS

    • Types and Names
    • Metadata
    • Subscriptions
    • Memberships

    MESSAGES

    • Sending Messages
    • Message Storage
    • Unread Counts
    • File Upload
    • Typing Indicators
    • Read Receipts
    • Emoji Reactions
    • Update Messages
    • Delete Messages
    • Message Webhooks

    PUSH NOTIFICATIONS

    • Overview

    MODERATION

    • Profanity Filters
    • Flag Messages
    • Ban Users
    • Mute Users
    • Spam Prevention

    INTEGRATIONS

    • Overview
    • Content Moderation
    • Image Moderation
    • Language Translation
    • Chatbots
    • GIFs
    • Stickers

Moderation Dashboard

  • Overview
  • Getting Started
  • FEATURES

    • Automatic Text Moderation
    • Automatic Image Moderation
    • Manual Message Moderation
    • Manual User Moderation
    • User Management
    • Channel Management
  • Required Configuration

Debug Console
Network Status

Sending images and files

The Files 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 Sharing Images and Files.

The following code sends a file cat_picture.jpg to the channel my_channel:

JavaScript
Java
C#
Objective-C
Python
Unity
Swift

Go to SDK

// 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';

const myFile = fs.createReadStream('./cat_picture.jpg');

const result = await pubnub.sendFile({
channel: 'my_channel',
file: { stream: myFile, name: 'cat_picture.jpg', mimeType: 'application/json' },
});

// in React and React Native
const result = await pubnub.sendFile({
channel: 'my_channel',
message: {
test: 'message',
value: 42
},
file: {
uri: imageUri,
name: 'cat_picture.jpg',
mimeType: 'image/jpeg',
},
});

Go to SDK

pubnub.sendFile()
.channel("my_channel"
.fileName("cat_picture.jpg")
.inputStream(inputStream)
.cipherKey("my_cipher_key")
.message("Look at this photo!")
.async(new PNCallback<PNFileUploadResult>() {
@Override
public void onResponse(PNFileUploadResult result, PNStatus status) {
if (!status.isError()) {
System.out.println("send timetoken: " + result.getTimetoken());
System.out.println("send status: " + result.getStatus());
System.out.println("send fileId: " + result.getFile().getId());
System.out.println("send fileName: " + result.getFile().getName());
}
System.out.println("send status code: " + status.getStatusCode());
}
});

Go to SDK

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));
}

Go to SDK

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
* why the request may have failed.
*
* Check 'status.data.fileUploaded' to determine whether to resend the
* request or if only file message publish should be called.
*/

}
}];

Go to SDK

# 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

fd = open("cat_picture.jpg", "rb") as fd:
pubnub.send_file().
channel("my_channel").
file_name("cat_picture.jpg").
message({"test_message": "test"}).
should_store(True).
ttl(222).
file_object(fd.read()).
cipher_key("secret").pn_async(callback)

Go to SDK

pubnub.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);
}
});

Go to SDK

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)")
}
}

Clients 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"
    }
}
←Unread CountsTyping Indicators→
  • Send a file
© PubNub Inc. - Privacy Policy