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:

// 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 lines

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"
}
}
Last updated on
On this page