File Sharing API for Android SDK

Unsupported docs

PubNub no longer maintains Android SDK docs, but our Java SDK or Kotlin SDK are fully compatible with the Android platform and you can use them to build mobile apps, ensuring stable software development.

Use the Files API to upload and share files up to 5 MB on PubNub. Common use cases include social apps that share images and healthcare apps that share medical records.

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 a file or data to the specified channel.

Method(s)​

1pubnub.sendFile()
2 .channel(String)
3 .fileName(String)
4 .inputStream(InputStream)
5 .cipherKey(String)
6 .ttl(Integer)
7 .shouldStore(Boolean)
8 .message(Object)
9 .meta(Object)

| Parameter | Type | Required | Default | Description | | :-------- | :-------- | :-------- |: --- | :--- | | channel | String | Yes | n/a | Channel for the file. | | fileName | String | Yes | n/a | Name of the file to send. | | inputStream | InputStream | Yes | n/a | Input stream with file content. | | cipherKey | String | Optional | PNConfiguration#cipherKey | Key used to encrypt uploaded data. If not provided, the cipherKey in PNConfiguration is used if configured. | | ttl | Integer | Optional | n/a | How long the message should be stored in the channel's storage. | | shouldStore | Boolean | Optional | true | Whether to store the published file message in the channel history. | | message | Object | Optional | n/a | Message to send along with the file to the specified channel. | | meta | Object | Optional | n/a | Metadata object that can be used with the filtering capability. | For details on the method that publishes the file message, see Publish file message.

Sample code​

1pubnub.sendFile()
2 .channel("my_channel"
3 .fileName("cat_picture.jpg")
4 .inputStream(inputStream)
5 .cipherKey("my_cipher_key")
6 .message("Look at this photo!")
7 .async(new PNCallback<PNFileUploadResult>() {
8 @Override
9 public void onResponse(PNFileUploadResult result, PNStatus status) {
10 if (!status.isError()) {
11 System.out.println("send timetoken: " + result.getTimetoken());
12 System.out.println("send status: " + result.getStatus());
13 System.out.println("send fileId: " + result.downloadFile().getId());
14 System.out.println("send fileName: " + result.downloadFile().getName());
15 }
show all 18 lines

Response​

1{
2 "timetoken": 15957709330808500,
3 "status": 200,
4 "file": {
5 "id": "d9515cb7-48a7-41a4-9284-f4bf331bc770",
6 "name": "cat_picture.jpg"
7 }
8}

Returns​

The sendFile() operation returns a PNFileUploadResult with the following properties:

Property NameTypeDescription
timetokenLongA representation of the timetoken when the message was published.
statusIntegerRemote call return code.
filePNBaseFileUploaded file information.

PNBaseFile contains the following properties:

Property NameTypeDescription
idLongId of the uploaded file.
nameStringName of the upload 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.

1// Build push payloads using the helper
2 PushPayloadHelper pushPayloadHelper = new PushPayloadHelper();
3
4 // APNS (iOS) configuration
5 PushPayloadHelper.APNSPayload apnsPayload = new PushPayloadHelper.APNSPayload();
6
7 APS aps = new APS();
8 Map<String, String> alert = new HashMap<>();
9 alert.put("title", "New File");
10 alert.put("body", "A file was shared");
11 aps.setAlert(alert);
12 aps.setSound("default");
13 apnsPayload.setAps(aps);
14
15 // APNS2 targeting
show all 67 lines

For 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(Integer)
4 .next(String)
* required
ParameterDescription
channel *
Type: String
Default:
n/a
Channel to get list of files.
limit
Type: Integer
Default:
100
Number of files to return. Minimum value is 1, and maximum is 100.
next
Type: String
Default:
n/a
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.

Sample code​

1pubnub.listFiles()
2 .channel("my_channel")
3 .async(new PNCallback<PNListFilesResult>() {
4 @Override
5 public void onResponse(PNListFilesResult result, PNStatus status) {
6 if (!status.isError()) {
7 System.out.println("files status: " + result.getStatus());
8 System.out.println("files status: " + result.getNext());
9 System.out.println("files status: " + result.getCount());
10 System.out.println("files status: " + result.getCount());
11 for (PNUploadedFile file : result.getData()) {
12 System.out.println("files fileId: " + file.getId());
13 System.out.println("files fileName: " + file.getName());
14 System.out.println("files fileSize: " + file.getSize());
15 System.out.println("files fileCreated: " + file.getCreated());
show all 20 lines

Response​

1{
2 "data":[
3 {
4 "name":"cat_picture.jpg",
5 "id":"d9515cb7-48a7-41a4-9284-f4bf331bc770",
6 "size":25778,
7 "created":"202007 - 26T13:42:06Z"
8 }],
9 "status": 200
10 "totalCount": 1,
11 "next": null,
12 "prev": null
13}

Returns​

The listFiles() operation returns a PNListFilesResult with the following properties:

Property NameTypeDescription
timetokenLongA representation of the timetoken when the message was published.
statusIntegerRemote call return code.
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.
countIntegerNumber of files returned.
dataListList of channel files.

PNUploadedFile contains the following properties:

Property NameTypeDescription
idLongID of the uploaded file.
nameStringName of the uploaded file.
sizeIntegerSize of the uploaded file.
createdStringTime of creation.

Get file URL​

Generate a URL that can be used to download a file from the target channel.

Method(s)​

1pubnub.getFileUrl()
2 .channel(String)
3 .fileName(String)
4 .fileId(String)
* required
ParameterDescription
channel *
Type: String
Name of channel to which the file has been uploaded.
fileName *
Type: String
Name under which the uploaded file is stored.
fileId *
Type: String
Unique identifier for the file, assigned during upload.

Sample code​

1pubnub.getFileUrl()
2 .channel("my_channel")
3 .fileName("cat_picture.jpg")
4 .fileId("d9515cb7-48a7-41a4-9284-f4bf331bc770")
5 .async(new PNCallback<PNFileUrlResult>() {
6 @Override
7 public void onResponse(PNFileUrlResult result, PNStatus status) {
8 if (!status.isError()) {
9 System.out.println("getUrl fileUrl: " + result.getUrl());
10 }
11 System.out.println("getUrl status code: " + status.getStatusCode());
12 }
13 });

Response​

1{
2 "url":"http://ps.pndsn.com/v1/files/demo/channels/my_channel/files/d9515cb7-48a7-41a4-9284-f4bf331bc770/cat_picture.jpg?pnsdk=PubNub-Java-Unified/4.32.0&timestamp=1595771548&uuid=pn-9ce9e988-8e04-40bf-90c4-ebe170478f7d"
3}

Returns​

The getFileUrl() operation returns a PNFileUrlResult with the following property:

Property NameTypeDescription
urlStringURL to be used to download the requested file.

Download file​

Download a file from the specified channel.

Method(s)​

1pubnub.downloadFile()
2 .channel(String)
3 .fileName(String)
4 .fileId(String)
5 .cipherKey(String)
* required
ParameterDescription
channel *
Type: String
Name of channel to which the file has been uploaded.
fileName *
Type: String
Name under which the uploaded file is stored.
fileId *
Type: String
Unique identifier for the file, assigned during upload.
cipherKey
Type: String
Key used to decrypt downloaded data. If not provided, the SDK uses the CipherKey from the PNConfiguration.

Sample code​

1pubnub.downloadFile()
2 .channel("my_channel")
3 .fileName("cat_picture.jpg")
4 .fileId("d9515cb7-48a7-41a4-9284-f4bf331bc770")
5 .cipherKey("my_cipher_key")
6 .async(new PNCallback<PNDownloadFileResult>() {
7 @Override
8 public void onResponse(PNDownloadFileResult result, PNStatus status) {
9 if (!status.isError()) {
10 System.out.println("downloadFile fileName: " + result.getFileName());
11 System.out.println("downloadFile byteStream: " + result.getByteStream());
12 }
13 System.out.println("downloadFile status code: " + status.getStatusCode());
14 }
15 });

Response​

1{
2 "fileName": "cat_picture.jpg",
3 "byteStream": <file data>
4}

Returns​

The downloadFile() operation returns a PNDownloadFileResult with the following properties:

Property NameTypeDescription
fileNameStringName of the downloaded file.
byteStreamInputStreamInput stream containing all bytes of the downloaded file.

Delete file​

Delete a file from the specified channel.

Method(s)​

1pubnub.deleteFile()
2 .channel(String)
3 .fileName(String)
4 .fileId(String)
* required
ParameterDescription
channel *
Type: String
The channel from which to delete the file.
fileName *
Type: String
Name of the file to be deleted.
fileId *
Type: String
Unique identifier of the file to be deleted.

Sample code​

1pubnub.deleteFile()
2 .channel("my_channel")
3 .fileName("cat_picture.jpg")
4 .fileId("d9515cb7-48a7-41a4-9284-f4bf331bc770")
5 .async(new PNCallback<PNDeleteFileResult>() {
6 @Override
7 public void onResponse(PNDeleteFileResult result, PNStatus status) {
8 if (!status.isError()) {
9 System.out.println("delete status code: " + result.getStatus());
10 }
11 System.out.println("delete status code: " + status.getStatusCode());
12 }
13 });

Response​

1{
2 "status": 200
3}

Returns​

The deleteFile() operation returns a PNDeleteFileResult with the following property:

Property NameTypeDescription
StatusIntegerReturns a status code.

Publish file message​

Publish file message from specified Channel.

Method(s)​

1pubnub.publishFileMessage()
2 .channel(String)
3 .fileName(String)
4 .fileId(String)
5 .message(Object)
6 .meta(Object)
7 .shouldStore(Boolean)
* required
ParameterDescription
channel *
Type: String
Default:
n/a
Name of channel to publish file message.
fileName *
Type: String
Default:
n/a
Name of the file.
fileId *
Type: String
Default:
n/a
Unique identifier of the file.
message
Type: Object
Default:
n/a
The payload.
meta
Type: Object
Default:
n/a
Meta data object which can be used with the filtering ability.
shouldStore
Type: Boolean
Default:
true
Whether to store this message in history. Set to false to not store it. By default, messages are stored according to the retention policy set on your key.

Sample code​

1pubnub.publishFileMessage()
2 .channel("my_channel")
3 .fileName("cat_picture.jpg")
4 .fileId("d9515cb7-48a7-41a4-9284-f4bf331bc770")
5 .message("This is a sample message")
6 .async(new PNCallback<PNFileUploadResult>() {
7 @Override
8 public void onResponse(PNFileUploadResult result, PNStatus status) {
9 if (!status.isError()) {
10 System.out.println("send timetoken: " + result.getTimetoken());
11 System.out.println("send status: " + result.getStatus());
12 System.out.println("send fileId: " + result.downloadFile().getId());
13 System.out.println("send fileName: " + result.downloadFile().getName());
14 }
15 System.out.println("send status code: " + status.getStatusCode());
show all 17 lines

Response​

1{
2 "timetoken": 15957709330808500,
3 "status": 200,
4 "file": {
5 "id": "d9515cb7-48a7-41a4-9284-f4bf331bc770",
6 "name": "cat_picture.jpg",
7 }
8}

Returns​

The sendFile() operation returns a PNFileUploadResult which contains the following properties:

Property NameTypeDescription
timetokenLongThe timetoken at which the message was published.
statusIntegerRemote call return code.
filePNBaseFileUploaded file information.

PNBaseFile contains the following properties:

Property NameTypeDescription
idLongUnique identifier of the uploaded file
nameStringName of the uploaded file

Was this page useful?

Last updated on