How can I use DownloadProgressChangedEventHandler in asp.net mvc?

I have a website where I want to download a file from the WebClient Class.

For example, I have a URL that I want to download. in a console application, these methods and code work correctly.

This is sample code in a 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 works correctly in a console application.

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

for asp.net mvc he should like it (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) is very important for the job, because I want to create a progress bar on the client side.

I think this is the best way to do this. but how can it?

+5
source share
1 answer

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); } 
+2
source

Source: https://habr.com/ru/post/1268488/


All Articles