gpt4 book ai didi

c# - 如何在 asp.net mvc 中使用 DownloadProgressChangedEventHandler?

转载 作者:太空狗 更新时间:2023-10-29 23:36:30 30 4
gpt4 key购买 nike

我有一个网站,我想用 WebClient 类下载文件。

例如我有我想下载它的网址。在控制台应用程序中,此方法和代码可以正常工作。

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

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:\\temp\1.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);
}

关于c# - 如何在 asp.net mvc 中使用 DownloadProgressChangedEventHandler?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44336420/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com