Using download API

Introduction

Tizen allows you to download files from the Internet (by given URL) using the Download API. It can be handy when creating download manager applications or applications that need to download extra content from the server. Download API gives you the possibility to monitor download progress and status.

Managing downloads

To download file we have to create request first. You can do it by creating object with tizen.DownloadRequest constructor, which takes URL as the first argument.

var request = new tizen.DownloadRequest('http://download.tizen.org/tools/README.txt');

Other arguments are optional but let’s examine them.

Destination (“destination” attribute of the request object)

It’s the string argument that tells Download Manager where to save given file. The default value is “downloads” which means that file will be save to the Download director on your device. Other possible values with descriptions are listed below:

  • images - the images location.
  • videos - the videos location.
  • music - the sounds location.
  • documents - the documents location.

File name (“fileName” attribute of the request object)

By default files are saved with their original name (plus number when file with the given name already exists in the given directory). However, we can change this name to any name we want by filling this attribute.

Network type (“networkType” attribute of the request object)

This attribute indicates the network type in which download is allowed. There are three possible values: CELLULAR, WIFI and ALL (default value).

HTTP headers (“httpHeader” attribute of the request object)

A set of extra headers that will be sent to the server when making request for file download. Sample code of making request object could look like this:

var request = new tizen.DownloadRequest(
    'http://download.tizen.org/tools/README.txt', // File URL
    'Downloads', // Destination directory
    'new-file-name.txt', // New file name
    'ALL', // Network type
    { // HTTP headers
        'Pragma': 'no-cache',
        'X-Agent': 'FileDownloader'
    }
);

Having DownloadRequest object, we can now pass it to the tizen.download.start function that will start process of downloading file. However maybe we would like to listen to some download events like when it starts or how big fraction of the file is already downloaded. To make it possible we have to pass object with events listeners as a second argument of the tizen.download.start function.

We can choose from 5 different download events:

  • onprogress - function (id, receivedSize, totalSize)
  • onpaused - function (id)
  • oncanceled - function (id)
  • oncompleted - function (id, fullPath)
  • onfailed - function (id, error)

Arguments names are quite obvious and don’t need any explanation, maybe except the oncompleted event and fullPath argument which indicates the full path to the downloaded file including file name.

tizen.download.start function returns download id that we should store, if we want to influence file’s downloading process. Having this id we can cancel, pause or resume given download:

var id = tizen.download.start(request);
tizen.download.pause(id);
tizen.download.resume(id);
tizen.download.cancel(id);

We can also check the state of given download using getState function. For more detailed information I refer you to the official Download API documentation.

Sample application

There is sample application attached to this article that demonstrates creation of the simple Download Manager. The application screenshot is presented in the image below:

Screenshot of the sample application.

Application consists of input field where you can enter file URL and download button on the right which starts download process. Progress of files downloading process is presented in the form of list below the form. User can pause, resume or cancel each download.

Let’s investigate code to see how application works. The main part of the application is items object that stores list of all download ids as keys and some additional jQuery objects correlated with the given file. We store it in the object instead of array because of the efficiency reason. Download ids are numbers but mostly big numbers, so indexing array with those numbers would cause allocation of huge amount of data that is not used. Additionally objects’ keys are indexed so access to them is very fast.

Adding files to download

After clicking Download… button we invoke the following chunk of code:

inputs.download.on('click', function () {
    var url = inputs.url.val(),
        fileName = url.split('/').pop();

    if (url) {
        inputs.url.val('');

        var li = $(template.html()),
            name = li.find('.name'),
            bar = li.find('.bar'),
            percentage = li.find('.percentage'),
            play = li.find('.icon-play'),
            pause = li.find('.icon-pause'),
            cancel = li.find('.icon-cancel');

        var downloadRequest = new tizen.DownloadRequest(url, 'downloads'),
            id = tizen.download.start(downloadRequest, listeners);

        name.html(fileName);
        li.attr('id', id);
        list.append(li);

        items[id] = {
            li: li,
            name: name,
            bar: bar,
            percentage: percentage,
            play: play,
            pause: pause,
            cancel: cancel
        };
    }
});

First, we take value of the URL input field, get file name and clear URL. Next thing we do is creation of the list item element (HTML code) by taking HTML code from the template element that is hidden. We append generated element to the UL element stored inside list variable.

We take jQuery handles for all the major elements in this list item element, i.e. name field, progress bar, percentage value of the download and play, pause and cancel buttons. Next, jQuery handles are stored inside items object under the key name that is equal to the download id.

Defining event listeners

We define two listeners that are passed to the tizen.download.start function. As you can see in the code below, we calculate percentage value of the download progress and update corresponding HTML element’s text attribute as well as width of the progress bar.

var listeners = {
    onprogress: function (id, receivedSize, totalSize) {
        var item = items[id];
        if (item) {
            var percentage = Math.round(receivedSize / totalSize * 100) + '%';
            item.bar.css({ width: percentage });
            item.percentage.text(percentage);
        }
    },
    oncompleted: function (id) {
        remove(id);
    }
};

When download is completed, we call remove function that clears information about downloaded file and removes file’s DOM element from the download list.

var remove = function (id) {
    var item = items[id];
    item.li.fadeOut('slow', function () {
        item.li.remove();
        delete items[id];
    });
};

Last one major thing we do is pausing, resuming and canceling download. It’s quite simple and requires only checking the state of the download and running proper function with the download id.

list.on('click', '.icon-pause', function () {
    var id = $(this).parents('li:first').attr('id'),
        item = items[id];
    
    if (item && tizen.download.getState(id) === 'DOWNLOADING') {
        tizen.download.pause(id);
        item.pause.hide();
        item.play.show();
    }
});

Summary

Download API can be handy when creating download managers. Without it, developer would need to take care of all the operations that are required to manage download process. With Download API, downloading file can’t be simpler. I hope that after reading this article you will be able to create one by yourself.

File attachments: