gpt4 book ai didi

c# - 从另一台服务器 ASP.NET 下载文件时如何在网页中显示进度

转载 作者:行者123 更新时间:2023-11-30 13:04:36 25 4
gpt4 key购买 nike

在我的一个网页中,控件基于另一个远程服务器中某些 xml 文件中指定的值。所以我需要在 page_load() 中下载并解析它们并显示控件。问题是 xml 文件相当大大,需要很多时间。所以我想使用 webclient.DownloadFileAsync() 方法下载 xml 文件,并将信息显示为下载了多少字节。

我已经编写了下载文件的代码,但不知道如何在 DownloadProgressChanged 事件上更新页面。我认为它需要 ajax 方法。请指导我如何做。

aspx 页面

<form id="form1" runat="server">   
</asp:ScriptManager>
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>

代码隐藏(感谢另一个 stackoverflow 问题)

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private Queue<string> _downloadUrls = new Queue<string>();

private void downloadFile(IEnumerable<string> urls)
{
foreach (var url in urls)
{
_downloadUrls.Enqueue(url);
}
// Starts the download
Label1.Text = "Downloading...";
DownloadFile();
}

private void DownloadFile()
{
if (_downloadUrls.Any())
{
WebClient client = new WebClient();
client.UseDefaultCredentials = true;
client.DownloadProgressChanged += client_DownloadProgressChanged;
client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);

var url = _downloadUrls.Dequeue();
string FileName = url.Substring(url.LastIndexOf("/") + 1,
(url.Length - url.LastIndexOf("/") - 1));

client.DownloadFileAsync(new Uri(url), Server.MapPath(".") + "\\" + FileName);
//lblFileName.Text = url;
return;
}
// End of the download
Label1.Text = "Download Complete";
}

void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
DownloadFile();
}

void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100;
// Label1.Text = percentage.ToString();
}

protected void Button1_Click(object sender, EventArgs e)
{
List<string> urls = new List<string>();
urls.Add("http://abcd.com/1.xml");
urls.Add("http://abcd.com/2.xml");
downloadFile(urls);
}
}

最佳答案

关于c# - 从另一台服务器 ASP.NET 下载文件时如何在网页中显示进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8268705/

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