Download file from Web asynchronously

If you want to download large file from the web site you'll need to do this asynchronously (which means that your application can do other things while the file is being downloaded. This can be done easilly thanks to .NET class WebClient. For smaller files you can use solution described in article Download file from Web

In the following example we will use DownloadFileAsync method that takes two parameters. First parameter specifies Url that should be downloaded and the second one is path on the local computer where the fill will be saved. We also use .NET event handlers that allows WebClient class to send back information about the downloading (when the downloading is completed and the progress during the download). The WebClient class has two important events - first event (DownloadFileCompleted) is called when the download is completed and the second (DownloadProgressChanged) is called several times during the download with the current progress information.

<?php

import namespace System;
import namespace System:::ComponentModel;
import namespace System:::Net;

// Class that can be used for asynchronous file download
class Downloader
{
  private $done = false;
	
  public function StartDownload($path, $name)
  {
    // first we need to create WebClient class
    $client = new WebClient;

    // attach two event handlers
    // it is currently not possible to use "+=" syntax known from C#
    $client->DownloadFileCompleted->Add(new AsyncCompletedEventHandler(array($this, "DownloadCompleted")));
    $client->DownloadProgressChanged->Add(new DownloadProgressChangedEventHandler(array($this, "ProgressChanged")));

    // start the download
    $client->DownloadFileAsync(new Uri($path), $name);
  }

  // called by WebClient after successful download
  private function DownloadCompleted($sender, $e)
  {
    echo "Download Complete";
    $this->done = true;
  }

  // called several times during the download
  private function ProgressChanged($sender, $e)
  {
    echo $e->ProgressPercentage."\n";
  }
	
  // tells user of this class whether download is already completed
  public function IsDownloaded()
  {
    return $this->done;
  }
} 


And finally, little example that shows how to use this class (this example uses Thread .NET class to sleep the process while downloading the file):
$tst = new Downloader;
$tst->StartDownload(http://www.php-compiler.net", "C:\\test.html");

while(!$tst->IsDownloaded())
{
  // do something reasonable here :-)
  System:::Threading:::Thread::Sleep(10);
}
fgets(STDIN); 

Last edited Oct 22, 2006 at 12:52 AM by tomasp, version 2

Comments

No comments yet.