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

时间:2011-11-25 11:50:14

标签: c# asp.net webclient-download

在我的一个网页中,控件基于另一个远程服务器中某些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);
  }
}