1. Home
  2. Docs
  3. UniREST Solution 3.5
  4. UniREST Client
  5. Online Files
  6. Download / Upload Files

Download / Upload Files

The UniREST solution is able to download and upload files. This means that your Game can download any kind of file in the target device and upload any kind of file into your Server.

How it works

The download/upload system is built on top of the UnityWebRequest engine, so it inherits the advantages to use this Unity core functionality (cross-platform compatibility, Unity integration, and so on).

Security

Download and upload functionalities are common operations that use common technologies, and they are mainly managed by the UnityWebRequest engine. While the download operation has no specific security checks, the upload operation is controlled, server-side, by the UniREST Server application. In this case, when your Game uploads a file in your Server, the UniREST Client asks for the authorization for doing it.


Download a File

Create an Instance

The first thing to do is to declare an instance of the UniRESTClient.Download class. This will initialize an instance able to download one or more files.

var myDownloadInstance = new UniRESTClient.Download();
Returned valueDescription
Download objectA Download object.

Listing the file to download

Once the Download instance is ready, you must fill it with the list of files you want to download and, optionally, where they have to be saved as a file. To collect this list you have to use the FromUrl(), the FromGame() or the FromUser() methods.

myDownloadInstance.FromURL(fileURL, localDestinationFolder);
myDownloadInstance.FromGame(fileName, localDestinationFolder);
myDownloadInstance.FromUser(fileName, localDestinationFolder);
.FromURLThe file is downloadable directly from the given HTTP(s) URL.
Example: http://www.mywebsite.com/assets/myfile.fbx
.FromGameThe file to download is placed into the Game Folder.
Example: level01/models/buildings.fbx
.FromUserThe file to download is placed into the user’s dedicated folder.
Example: myassets/myfile.fbx
ParameterData-typeDescription
fileURLstringThe direct link to the file to download.
fileNamestringThe name of the file to download. It can contains a path to subfolders.
localDestinationFolderstringThe local folder path where to store the downloaded file (the path only).
If set, the downloaded file will be stored in that folder.
If not set, the downloaded file will be returned directly as byte[] data.

Starting the download

To start a download, simply call the Start() method. All the collected files will be downloaded one by one.

myDownloadInstance.Start();

Getting the downloaded data

The downloaded data and files get available once the download process is completed.

Since the process takes place in the background, you have to catch when the download is finished. See the Download / Upload Process Management paragraph.

Upload a File

Create an Instance

The first thing to do is to declare an instance of the UniRESTClient.Upload class. This will initialize an instance able to upload one or more files.

var myUploadInstance = new UniRESTClient.Upload();
Returned valueDescription
Upload objectAn Upload object.

Listing the file to upload

Once the Upload instance is ready, you must fill it with the list of files you want to upload and where they have to be saved in your Server. To collect this list you have to use the ToGame() or the ToUser() methods.

myUploadInstance.ToGame(localFileName, destinationFolder = '');
myUploadInstance.ToUser(localFileName, destinationFolder = '');
.ToGameThe file will be uploaded into the Game Folder.
.ToUserThe file will be uploaded into the user’s dedicated folder.
ParameterData-typeDescription
localFileNamestringThe path to the file to upload.
destinationFolderstring
(optional)
In which subfolder(s) the file has to be uploaded. If empty, the file will be simply uploaded into the root Game or User folder.

Starting the upload

To start an upload, simply call the Start() method. All the collected files will be uploaded one by one.

myUploadInstance.Start();
Since the upload process takes place in the background, you have to catch when the upload is finished. See the Download / Upload Process Management paragraph.

Download / Upload Process Management

Introduction

The download and upload processes take place in the background. This means that your Unity Game doesn’t know if the process is finished, is in progress or is stopped by an error.

You can easily manage that 3 situations defining 3 functions that the Download / Upload instance has to call (callback functions).

Defining the Callback functions

The use of callback functions in optional, but it’s strictly recommended. Especially the use of the onCompleteCallBack function that allows you to know when the process is completed.

To define the callback functions simply create the functions you want to use and assign them to the onCompleteCallBack, onProgressCallBack, onErrorCallBack instance’s property.

onCompleteCallBackThe callback function will be called once the process will be successfully completed.
onProgressCallBackThe callback function will be called repeatedly during the process until it finishes or goes into error.
onErrorCallBackThe callback function will be called in case of error.

A callback function must have the UniRESTClient.Download.Status / UniRESTClient.Upload.Status parameter. In this parameter, both the Download and Upload engines will store information about the process and the files (process status).

void StartUpload() 
{
      var myDownloadInstance = UniRESTClient.Download();
      myDownloadInstance.onCompleteCallBack = OnDownloadFinished;


      var myUploadInstance = UniRESTClient.Upload();
      myUploadInstance.onCompleteCallBack = OnUploadFinished;
 }

void OnDownloadFinished(UniRESTClient.Download.Status s) {
      // Do something when the download is complete...
      // The 's' variable contains the download status details.
}

void OnUploadFinished(UniRESTClient.Upload.Status s) {
      // Do something when the upload is complete...
      // The 's' variable contains the upload status details.
}

Process Status

During a download/upload process, the UniRESTClient class constantly collects information about the process status. This information is stored and updated into the instance’s status property.

Ideally, you can use the status property inside the onProgessCallBack callback function for showing or using the progress information.

The status property exposes the following information:

PropertyData-typeDescription
status.currentFileIndexintThe index (starting from 1) of the file currently being processed.
status.currentFileSizeintThe size, in bytes, of the file currently being processed.
status.currentFileProgressfloatThe percentage of the file currently being processedas a value from 0 to 1 (e.g. 0.2 = 20%).
status.currentDestionationFilestringThe full path to the file currently being processed if it will be saved locally.
status.currentFileURLstringThe URL of the file currently being processed.
status.totalFilesintThe total number of files currently being processed.
status.totalBytesintThe total number of bytes that will be processed.
status.totalProgressfloatThe percentage of the whole process as a value from 0 to 1 (e.g. 0.2 = 20%).
status.speedfloatThe processing speed as the number of bytes per second.
status.errorstringThe error message thrown by the system in case of error.
. . .
      myFiles.onProgessCallBack = OnUploadProgress();
. . .
}

void OnUploadProgress() {

      // Uploading 1 of 4 files.
      Debug.Log("Uploading " + myFiles.status.currentFileIndex + " of " + myFiles.status.totalFiles + " files.");

      // Current file: my3Dmodel.fbx
      Debug.Log("Current file: " + myFiles.status.currentFileURL);

      // Progress: 0.8% - Total: 0.1%
      Debug.Log("Progress: " + myFiles.status.currentFileProgress + "% - Total: " + myFiles.status.totalProgress + "%");

      // Speed: 1658220 bytes/sec
      Debug.Log("Speed: " + myFiles.status.speed + " bytes/sec");

}

progressDelaySpeed

Both Download and Upload classes have the progressDelaySpeed property. This property, set to 250 by default, is the number of milliseconds to wait before getting and releasing all the information about the Process status.

This means that, by default, the information of the status property is collected about 4 times per second.

This is an acceptable value for generic scenarios, but it affects the precision with which the downloading/uploading progress is released. In some situations, you may want to have higher precision, for example, because you are showing a progress bar and it’s not very precise.

To get higher precision, just reduce the progressDelaySpeed (with a certain precaution).


filesData

If you hadn’t set a local destination folder for downloaded files, the downloaded files are released as byte arrays stored in the filesData property. This is a List of byte arrays. Each byte array is the data obtained from each downloaded file, in the same order they have been listed in the Download instance.


Shared methods

The following methods can be called by both Download and Upload instances.

Stop()

When called, the Stop() method interrupts the operation. The file transfer is not interrupted instantly, but it stops as soon as it can (this is an ordinary behaviour of the download/upload technology). Occasionally, this call may generate an error message in the Unity Console. It’s a generic, non-blocking message that can be ignored.

myInstance.Stop();

ConvertPercentage()

This method converts the percentage value from the status in a percentage string with the % symbol and, optionally, with a specific number of digits.

myInstance.ConvertPercentage(value, decimalPlaces = 0);

ConvertBytes()

This method converts the number of bytes from the status in a more readable string of Kilobytes, Megabytes and so on (including the used unit), and, optionally, with a specific number of digits.

myInstance.ConvertBytes(value, decimalPlaces = 1);