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

本文关键字:网页 显示 文件 下载 另一个 服务器 NET ASP | 更新日期: 2023-09-27 18:15:48

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

我已经写了代码来下载文件,但不知道如何更新DownloadProgressChanged事件的页面。我认为它需要ajax方法。请告诉我怎么做。

aspx page

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

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

试试这个:http://weblogs.asp.net/rrobbins/archive/2008/06/27/file-download-progress-bar.aspx