如何在ASP.NET MVC中使用下载Progresschangedeventhandler



我有网站,我想通过WebClient类下载文件。

例如,我有要下载的URL。在控制台应用程序中,此方法和代码正常工作。

这是控制台应用程序中的示例代码:

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);
    }

此示例代码在控制台应用程序中正确工作。

如何在ASP.NET MVC应用程序中使用此示例代码。

对于ASP.NET MVC,它应该喜欢这个(我认为(

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

对我来说,事件处理程序方法(downloader_downloadprogresschanged(工作非常重要,因为我想在客户端创建进度栏。

我认为这是做到这一点的最佳方法。但是怎么能?

您可以通过在项目中添加此代码来实现这一目标:

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);
}

相关内容

  • 没有找到相关文章

最新更新