Pages

Thursday, December 22, 2011

Download Multiple file Using Single HTTP Request

Unfortunately HTTP handle single request at a time. That's means Multiple files download is not possible using HTTP single request.
Multiple download can only be possible using following two ways.

1. Using java script where multiple popup can be open to download multiple files.

function callMulipleDownload() {
     fnOpen('1');
     fnOpen('2');
}
function fnOpen(f1) {
     window.open('/Home/Download/?type=' + f1);
}

This way is not recommended as many time popup is blocked on client browser.

2. Using WebClient DownloadFileAsync as follow.

private Queue _downloadUrls = new Queue();

private void downloadFile()
{
   _downloadUrls.Enqueue(Server.MapPath(@"~\Dwonload\Test-debug.apk"));
   _downloadUrls.Enqueue(Server.MapPath(@"~\Dwonload\Test1.apk"));

    DownloadFile();
}

private void DownloadFile()
{
    if (_downloadUrls.Any())
     {
       WebClient client = new WebClient();
       client.DownloadProgressChanged += client_DownloadProgressChanged;

       var url = _downloadUrls.Dequeue();
       Uri uri = new Uri(url);
       string FileName = Path.GetFileName(uri.LocalPath);

       client.DownloadFileAsync(new Uri(url), "D:\\Test4\\" + FileName);
      }
    else
      return;
    DownloadFile();
}

private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    DownloadFile();
}

void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    double bytesIn = double.Parse(e.BytesReceived.ToString());
    double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
    double percentage = bytesIn / totalBytes * 100;
}

No comments:

Post a Comment