Send files

Attach files to text messages to share information (support chats) or improve collaboration (social conversations).

Contrary to the Kotlin SDK, Kotlin Chat SDK lets users attach not one but multiple files to a single message. They can attach any format of the files, but the size of each file must be at most 5 MB.

Files are uploaded to a message sequentially - the more files you attach, the longer it will take for the files to upload. To improve user experience in your chat app, you can implement a progress bar indicating to the user how many files have already been uploaded.

Requires File Sharing

To store files with PubNub, you must enable File Sharing for your app's keyset in the Admin Portal, choose the storage region, and set the desired file retention period. Consider aligning the file retention period with the retention you set for Message Persistence to store messages and files for the same period of time.

Send files

You can attach files to a draft message and publish it using the send() method.

Method signature

To add files, you must add elements to the files field (MutableList<InputFile>) of a MessageDraft object.

Basic usage

Attach two files of different formats to a text message.

// create a draft message
val messageDraft = channel.createMessageDraft(isTypingIndicatorTriggered = channel.type != ChannelType.PUBLIC)

// add a listener
val listener = { elements: List<MessageElement>, suggestedMentions: PNFuture<List<SuggestedMention>> ->
updateUI(elements) // updateUI is your own function for updating UI
suggestedMentions.async { result ->
result.onSuccess { updateSuggestions(it) } // updateSuggestions is your own function for displaying suggestions
}
}
messageDraft.addChangeListener(listener)

// work on editing message with messageDraft.update(text)

// attach files
show all 21 lines

Get all message files

You can access the files property of the Message object to list all files attached to a single message.

Field signature

This field has the following signature:

val files: List<File>

Basic usage

List all files attached to the last message on the support channel.

val channel: Channel
// ...

// get the last message from the channel’s history
channel.getHistory(count = 1).async { historyResult ->
historyResult.onSuccess { historyResponse ->
val lastMessage = historyResponse.messages.firstOrNull()
if (lastMessage != null) {
// access the files property of the last message
val files = lastMessage.files

if (files.isNotEmpty()) {
println("The last message contains the following files:")
files.forEach { file ->
println("File Name: ${file.name}, File Type: ${file.type}")
show all 27 lines

Get all channel files

getFiles() returns all files attached to messages on a given channel.

Method signature

This method takes the following parameters:

channel.getFiles(
limit: Int?,
next: String?
): PNFuture<GetFilesResult>

Input

ParameterTypeRequiredDefaultDescription
limitIntNo100Number of files to return.
nextStringNon/aString token to get the next batch of files.

Output

ParameterTypeDescription
PNFuture<GetFilesResult>objectReturned object containing these fields: files, next, and total.
 → filesCollection<GetFileItem>Array containing file details.
 → nextStringRandom string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off.
 → totalIntTotal number of files.

GetFileItem contains the following properties:

ParameterTypeDescription
nameStringName of the file, like error-1.jpg.
idStringUnique identifier assigned to the file by PubNub, like 736499374.
urlStringFile's direct downloadable URL, like https://ps.pndsn.com/v1/files/demo/channels/support/files/736499374/error-1.jpg.

Basic usage

List all files published on the support channel.

val channel: Channel

fun fetchFiles(channel: Channel, next: String?) {
channel.getFiles(limit = 100, next = next).async { result ->
result.onSuccess { filesResult ->
filesResult.files.forEach { file ->
println("File name: ${file.name}, File URL: ${file.url}")
}

// Check if there is another page of results
if (filesResult.next != null) {
fetchFiles(channel, filesResult.next)
}
}.onFailure {
// handle error
show all 23 lines

Delete files

Delete sent files or files from published messages with the deleteFile() method.

Endpoint limitation

Due to a lack of search functionality in the PubNub Message Persistence API, once you delete the file, you cannot track which historical messages contained the deleted file to remove info about the file from those messages.

Method signature

This method takes the following parameters:

channel.deleteFile(
id: String,
name: String
): PNFuture<PNDeleteFileResult>

Input

ParameterTypeRequiredDefaultDescription
idStringYesn/aUnique identifier assigned to the file by PubNub.
nameStringYesn/aName of the file.

Output

TypeDescription
PNFuture<PNDeleteFileResult>Status code of the response.

Basic usage

Remove a file named error-screenshot.png from the support channel.

val channel: Channel
// ...

// delete the file named "error-screenshot.png" from the "support" channel
val fileId = "file-id-to-delete" // Replace this with the actual file ID
val fileName = "error-screenshot.png"

channel.deleteFile(fileId, fileName).async { result ->
result.onSuccess {
println("File '$fileName' successfully deleted from 'support' channel.")
}.onFailure {
// handle error
println("Error deleting file '$fileName': ${it.message}")
}
}
Last updated on