我有网站,我想用WebClient Class下载文件。
例如我有网址,我想下载它。在控制台应用程序中,此方法和代码正常工作
这是控制台应用程序中的示例代码:
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)非常重要,因为我想在客户端创建进度条。
我认为这是最好的方法。但怎么可能?
答案 0 :(得分:2)
您可以通过将此代码添加到项目中来实现此目的:
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);
}