Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Use DownloadProgressChangedEventHandler in asp.net mvc?

I have website that I want download file with WebClient Class .

For example I have url that I want download it . in console application this methods and code work correctly .

This is sample code in Console application :

public void DownloadFile(string sourceUrl, string targetFolder)
    {
        WebClient downloader = new WebClient();
        downloader.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0)");
        downloader.DownloadFileCompleted += new AsyncCompletedEventHandler(Downloader_DownloadFileCompleted);
        downloader.DownloadProgressChanged +=
            new DownloadProgressChangedEventHandler(Downloader_DownloadProgressChanged);
        downloader.DownloadFileAsync(new Uri(sourceUrl.Replace(@"\","")), targetFolder);
        while (downloader.IsBusy) { }
    }

private void Downloader_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        //Console.Write(e.BytesReceived + " " + e.ProgressPercentage);  

        Console.Write("%" + e.ProgressPercentage);
    }

this sample code work correctly in console application .

how can i use this sample code in asp.net mvc application .

for asp.net mvc it should like this (i think)

      public ActionResult DownloadPage()
    {
        string url = "https://rjmediamusic.com/media/mp3/mp3-256/Mostafa-Yeganeh-Jadeh.mp3";
        var downld = new DownloadManager();
        downld.DownloadFile(url, @"c:\\temp\1.mp3");
        return View();
    }

for me the event handler method (Downloader_DownloadProgressChanged) it very important to work because i want create progress bar in client side .

As i think this is best way to do that . but how can ?

like image 742
salar Avatar asked Oct 30 '22 07:10

salar


1 Answers

You can achieve this by adding this code to your project:

public void DownloadFile(string sourceUrl, string targetFolder)
{
    WebClient downloader = new WebClient();
    downloader.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0)");
downloader.DownloadFileCompleted += new AsyncCompletedEventHandler(Downloader_DownloadFileCompleted);
downloader.DownloadProgressChanged +=
    new DownloadProgressChangedEventHandler(Downloader_DownloadProgressChanged);    
downloader.DownloadFileCompleted += new AsyncCompletedEventHandler(Downloader_DownloadFileCompleted);
    downloader.DownloadProgressChanged +=
        new DownloadProgressChangedEventHandler(Downloader_DownloadProgressChanged);
    downloader.DownloadFileAsync(new Uri(sourceUrl.Replace(@"\","")), targetFolder);
    while (downloader.IsBusy) { }
}

private void Downloader_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    //Console.Write(e.BytesReceived + " " + e.ProgressPercentage);  

    Console.Write("%" + e.ProgressPercentage);
}
like image 65
Morteza Rastgoo Avatar answered Nov 09 '22 09:11

Morteza Rastgoo