File Sharing API for Unity SDK
You can upload and share files up to 5 MB on PubNub. Common uses include sharing images in chat apps and documents in healthcare.
When a file is uploaded on a channel, it's stored and managed using a storage service, and associated with your key. Subscribers to that channel receive a file event which contains a file ID, filename, and optional description.
Send file
Upload the file to a specified channel.
This method covers the entire process of sending a file, including preparation, uploading the file to a cloud storage service, and post-uploading messaging on a channel.
For the last messaging step, SendFile internally calls the PublishFileMessage method to publish a message on the channel.
The published message contains metadata about the file, such as the file identifier and name, enabling others on the channel to find out about the file and access it.
For details on the method that publishes the file message, see Publish file message.
Method(s)
1pubnub.SendFile()
2 .Channel(string)
3 .File(string|byte[])
4 .Texture(Texture2D | RenderTexture)
5 .FileName(string)
6 .Ttl(int)
7 .ShouldStore(bool)
8 .Message(string)
9 .Meta(Dictionary<string, object>)
10 .CustomMessageType(string)
11 .Execute(System.Action<PNFileUploadResult, PNStatus>)
Channelrequired#Channelfor the file.File#- Full path of the file with file name or an array of bytes.
When using an array of bytes, you must setFileName. Texture#- An instance of a
Textureobject. When you send aTexture, aMessagewith its size and format is added automatically. FileName#- Name of the file to send. You can use it to override the default file name.
TTL#- How long the message should be stored in the channel's storage.
ShouldStore#- Whether to store the published file message in the channel's history.
Message#- Message which should be sent along with file to specified
channel. Meta#- Dictionary
<string, object>with values which should be used by PubNub service to filter file messages. CustomMessageType#- A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes
-and underscores_are allowed. The value cannot start with special characters or the stringpn_orpn-.
Examples:text,action,poll. Executerequired#System.Actionof typePNFileUploadResult.ExecuteAsync#- Returns
Task<PNResult<PNFileUploadResult>>.
Deprecated parameter
The CipherKey parameter in this method is deprecated. We recommend that you configure the crypto module on your PubNub instance instead.
If you pass CipherKey as an argument, it overrides the crypto module configuration and the legacy encryption with 128-bit cipher key entropy is used.
Sample code
1using PubnubApi;
2using PubnubApi.Unity;
3using UnityEngine;
4
5public class SendFileExample : MonoBehaviour {
6 // Reference to a pubnub manager previously setup in Unity Editor
7 // For more details, see https://www.pubnub.com/docs/sdks/unity#configure-pubnub
8 [SerializeField] private PNManagerBehaviour pubnubManager;
9
10 // An editor-serialized string for the channel ID
11 [SerializeField] private string channelId = "my_channel";
12
13 // An editor-serialized string for the file path
14 [SerializeField] private string filePath = "cat_picture.jpg";
15
show all 53 linesResponse
1{
2 "Timetoken":15957709330808500,
3 "FileId":"d9515cb7-48a7-41a4-9284-f4bf331bc770",
4 "FileName":"cat_picture.jpg"
5}
Returns
The SendFile() operation returns a PNResult<PNFileUploadResult> which contains the following properties:
| Property Name | Type | Description |
|---|---|---|
Result | PNFileUploadResult | Returns a PNFileUploadResult object. |
Status | PNStatus | Returns a PNStatus object. |
PNFileUploadResult contains the following properties:
| Property Name | Type | Description |
|---|---|---|
Timetoken | long | Returns a PNFileUploadResult object. |
FileId | string | Returns the ID of the file. |
FileName | string | Returns the name of the file. |
Other examples
Send file with push notification
Trigger push notifications when sharing files
To send mobile push notifications when sharing a file, include pn_apns (for iOS) and/or pn_fcm (for Android) payloads in the message parameter of the SendFile method.
When PubNub detects these reserved keys, it automatically forwards the push notification to the appropriate push service (APNs or FCM) for all devices registered on the channel.
1var message = new MobilePushHelper()
2 .PushTypeSupport(new [] { PNPushType.APNS2, PNPushType.FCM })
3 .Title("New File")
4 .Body("Check out this file!")
5 .Apns2Data(new List<Apns2Data>()
6 {
7 new ()
8 {
9 targets = new List<PushTarget>()
10 {
11 new ()
12 {
13 environment = Environment.Production,
14 topic = "com.yourapp.bundleid"
15 }
show all 25 linesFor more details on push notification payload structure, see the iOS Push and Android Push documentation.
To prevent the sender from receiving their own push notification, add their device token to excluded_devices in the pn_push targets.
List channel files
Retrieve a list of files uploaded to a channel.
Method(s)
1pubnub.ListFiles()
2 .Channel(string)
3 .Limit(int)
4 .Next(string)
5 .QueryParam(Dictionary<string, object>)
6 .Execute(System.Action<PNListFilesResult, PNStatus>)
Channelrequired#Channelto get list of files.Limit#- Number of files to return.
Next#- Random 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.
QueryParam#- Dictionary
objectto pass name/value pairs as querystringparams with PubNub URL request for debug purpose. Executerequired#System.Actionof typePNListFilesResult.ExecuteAsync#- Returns
Task<PNResult<PNListFilesResult>>.
Sample code
1using PubnubApi;
2using PubnubApi.Unity;
3
4PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
5{
6 SubscribeKey = "demo",
7 PublishKey = "demo",
8 Secure = true
9};
10
11Pubnub pubnub = PubnubUnityUtils.NewUnityPubnub(pnConfiguration);
12
13// If you're using Unity Editor setup you can get the Pubnub instance from PNManagerBehaviour
14// For more details, see https://www.pubnub.com/docs/sdks/unity#configure-pubnub
15/*
show all 32 linesResponse
1{
2 "FilesList":[
3 {
4 "Name":"cat_picture.jpg",
5 "Id":"d9515cb7-48a7-41a4-9284-f4bf331bc770",
6 "Size":25778,
7 "Created":"2020-07-26T13:42:06Z"
8 }],
9 "Count":1,
10 "Next":null
11}
Returns
Returns PNResult<PNListFilesResult>.
| Property Name | Type | Description |
|---|---|---|
Result | PNListFilesResult | Returns a PNListFilesResult object. |
Status | PNStatus | Returns a PNStatus object. |
PNListFilesResult fields:
| Property Name | Type | Description |
|---|---|---|
FilesList | list<PNFileResult> | List of channel files. |
Count | int | Number of files returned. |
Next | string | Random 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. |
PNFileResult fields:
| Property Name | Type | Description |
|---|---|---|
Name | string | Name of the file. |
Id | string | ID of the file. |
Size | int | Size of the file. |
Created | string | Create date of the file. |
Get file URL
Generate a URL to download a file from the target channel.
Method(s)
1pubnub.GetFileUrl()
2 .Channel(string)
3 .FileId(string)
4 .FileName(string)
5 .Execute(System.Action<PNFileUrlResult, PNStatus>)
Channelrequired#- Name of
channelwithin which file with name has been uploaded. FileIdrequired#- Unique file identifier which has been assigned during file upload.
FileNamerequired#- Name under which uploaded file is stored for
channel. Executerequired#System.Actionof typePNFileUrlResult.ExecuteAsync#- Returns
Task<PNResult<PNFileUrlResult>>.
Sample code
1using PubnubApi;
2using PubnubApi.Unity;
3
4PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
5{
6 SubscribeKey = "demo",
7 PublishKey = "demo",
8 Secure = true
9};
10
11Pubnub pubnub = PubnubUnityUtils.NewUnityPubnub(pnConfiguration);
12
13// If you're using Unity Editor setup you can get the Pubnub instance from PNManagerBehaviour
14// For more details, see https://www.pubnub.com/docs/sdks/unity#configure-pubnub
15/*
show all 34 linesReturns
Returns PNResult<PNFileUrlResult>.
| Property Name | Type | Description |
|---|---|---|
Result | PNFileUrlResult | Returns a PNFileUrlResult object. |
Status | PNStatus | Returns a PNStatus object. |
PNFileUrlResult fields:
| Property Name | Type | Description |
|---|---|---|
Url | string | URL which can be used to download remote file with specified name and identifier. |
Download file
Download a file from the specified channel.
Method(s)
1pubnub.DownloadFile()
2 .Channel(string)
3 .FileId(string)
4 .FileName(string)
5 .Execute(System.Action<PNDownloadFileResult, PNStatus>)
Channelrequired#- Name of
channelwithin which file with name has been uploaded. FileIdrequired#- Unique file identifier which has been assigned during file upload.
FileNamerequired#- Name under which uploaded file is stored for
channel. Executerequired#System.Actionof typePNDownloadFileResult.ExecuteAsync#- Returns
Task<PNResult<PNDownloadFileResult>>.
Deprecated parameter
The CipherKey parameter in this method is deprecated. We recommend that you configure the crypto module on your PubNub instance instead.
If you pass CipherKey as an argument, it overrides the crypto module configuration and the legacy encryption with 128-bit cipher key entropy is used.
Sample code
1using PubnubApi;
2using PubnubApi.Unity;
3
4PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
5{
6 SubscribeKey = "demo",
7 PublishKey = "demo",
8 Secure = true
9};
10
11Pubnub pubnub = PubnubUnityUtils.NewUnityPubnub(pnConfiguration);
12
13// If you're using Unity Editor setup you can get the Pubnub instance from PNManagerBehaviour
14// For more details, see https://www.pubnub.com/docs/sdks/unity#configure-pubnub
15/*
show all 35 linesResponse
1{
2 //Call fileDownloadResult.SaveFileToLocal(<destination path>) to save file.
3 "FileBytes":"/9j/4AAQSkZJRgABAQEAkACQAAD/4RCERXhpZgAATU0AKgAAAAgABAE7AAIAAAAGAAAISodpAAQAAAABAAAIUJydAAEAAAA...<truncated due to lengthy data",
4 "FileName":"cat_picture.jpg"
5}
Returns
Returns PNResult<PNDownloadFileResult>.
| Property Name | Type | Description |
|---|---|---|
Result | PNDownloadFileResult | Returns a PNDownloadFileResult object. |
Status | PNStatus | Returns a PNStatus object. |
PNDownloadFileResult fields:
| Property Name | Type | Description |
|---|---|---|
FileBytes | byte[] | Bytes of the downloaded file. |
FileName | string | Name of the downloaded file. |
SaveFileToLocal(string) | n/a | Call with a destination path to save the file locally. |
Delete file
Delete a file from the specified channel.
Method(s)
1pubnub.DeleteFile()
2 .Channel(string)
3 .FileId(string)
4 .FileName(string)
5 .Execute(System.Action<PNDeleteFileResult, PNStatus>)
Channelrequired#- Name of
channelwithin which file with name needs to be deleted. FileIdrequired#- Unique file identifier of the file to be deleted.
FileNamerequired#- Name of the file to be deleted from the
channel. Executerequired#System.Actionof typePNDeleteFileResult.ExecuteAsync#- Returns
Task<PNResult<PNDeleteFileResult>>.
Sample code
1using PubnubApi;
2using PubnubApi.Unity;
3
4PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
5{
6 SubscribeKey = "demo",
7 PublishKey = "demo",
8 Secure = true
9};
10
11Pubnub pubnub = PubnubUnityUtils.NewUnityPubnub(pnConfiguration);
12
13// If you're using Unity Editor setup you can get the Pubnub instance from PNManagerBehaviour
14// For more details, see https://www.pubnub.com/docs/sdks/unity#configure-pubnub
15/*
show all 34 linesResponse
1{}
Returns
Returns PNResult<PNDeleteFileResult>.
| Property Name | Type | Description |
|---|---|---|
Result | PNDeleteFileResult | Returns a PNDeleteFileResult object. |
Status | PNStatus | Returns a PNStatus object. |
PNDeleteFileResult is empty.
Publish file message
Publish the uploaded file message to a specified channel.
This method is called internally by SendFile as part of the file-sending process to publish the message with the file (already uploaded in a storage service) on a channel.
This message includes the file's unique identifier and name elements, which are needed to construct download links and inform channel subscribers that the file is available for download.
You can call this method when SendFile fails and returns the status.operation === PNPublishFileMessageOperation error.
In that case, you can use the data from the status object to try again and use PublishFileMessage to manually resend a file message to a channel without repeating the upload step.
Method(s)
1pubnub.PublishFileMessage()
2 .Channel(string)
3 .FileId(string)
4 .FileName(string)
5 .Message(object)
6 .Meta(Dictionary<string, object>)
7 .ShouldStore(bool)
8 .CustomMessageType(string)
9 .Execute(System.Action<PNPublishFileMessageResult, PNStatus>)
Channelrequired#- Name of
channelto publish file message FileIdrequired#- Unique file identifier of the file.
FileNamerequired#- Name of the file.
Message#- The payload.
Meta#- Metadata object which can be used with the filtering ability.
ShouldStore#- Whether to store the message in history.
CustomMessageType#- A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes
-and underscores_are allowed. The value cannot start with special characters or the stringpn_orpn-.
Examples:text,action,poll. Executerequired#System.Actionof typePNPublishFileMessageResult.ExecuteAsync#- Returns
Task<PNResult<PNPublishFileMessageResult>>.
Sample code
1using PubnubApi;
2using PubnubApi.Unity;
3
4PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
5{
6 SubscribeKey = "demo",
7 PublishKey = "demo",
8 Secure = true
9};
10
11Pubnub pubnub = PubnubUnityUtils.NewUnityPubnub(pnConfiguration);
12
13// If you're using Unity Editor setup you can get the Pubnub instance from PNManagerBehaviour
14// For more details, see https://www.pubnub.com/docs/sdks/unity#configure-pubnub
15/*
show all 36 linesResponse
1{
2 "Timetoken":15957738720237858
3}
Returns
Returns PNResult<PNPublishFileMessageResult>.
| Property Name | Type | Description |
|---|---|---|
Result | PNPublishFileMessageResult | Returns a PNPublishFileMessageResult object. |
Status | PNStatus | Returns a PNStatus object. |
PNPublishFileMessageResult contains the following properties:
| Property Name | Type | Description |
|---|---|---|
Timetoken | long | Returns a long representation of the timetoken when the message was published. |