---
source_url: https://www.pubnub.com/docs/chat/sdks/messages/files
title: Sending images and files (deprecated)
updated_at: 2026-06-17T11:37:07.775Z
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Sending images and files (deprecated)

:::warning Use Chat SDKs
This documentation is deprecated. Use any of our dedicated [Chat SDKs](https://www.pubnub.com/docs/chat/overview) to quickly implement chat functionality in your application.
:::

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](https://www.pubnub.com/docs/sdks/javascript/api-reference/files#send-file) 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](https://www.pubnub.com/docs/general/files).

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

### JavaScript

```javascript
// 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',
  },
});
```

### Java

```java
pubnub.sendFile()
    .channel("my_channel"
    .fileName("cat_picture.jpg")
    .inputStream(inputStream)
    .cipherKey("my_cipher_key")
    .message("Look at this photo!")
    .async(result -> { /* check result */ });
```

### C#

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

### Objective-C

```objectivec
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.
         */
    }
}];
```

### Python

```python
# 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)
```

### Unity

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

### Swift

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

### Dart

```dart
import 'dart:io';
import 'package:pubnub/pubnub.dart';

void main() async {
  // Initialize the PubNub instance with your configuration
  var pubnub = PubNub(
    defaultKeyset: Keyset(
      subscribeKey: 'sub-c-abc-123',  // Replace with your subscribe key
      publishKey: 'pub-c-def-456'     // Replace with your publish key
    ),
  );

  // Read the file
  var inputFile = File('cat_picture.jpg').readAsBytesSync();

  // Send the file to the channel 'my_channel'
  try {
    var result = await pubnub.files.sendFile(
      'my_channel',
      'cat_picture.jpg',
      inputFile,
      fileMessage: 'Look at this photo!'
    );

    print(
      'File uploaded and file message published - timetoken ${result.timetoken}');
  } catch (e) {
    print('Failed to send file: $e');
  }
}
```

Clients can add a [File Listener](https://www.pubnub.com/docs/general/messages/receive#add-an-event-handler) to receive file events on their application and display the file in a browser or download the file.

Sample file event:

```json
{
"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"
    }
}
```