How to show progress on a web page when downloading a file from another ASP.NET server

On one of my web pages, the controls are based on the values โ€‹โ€‹defined in some xml files on another remote server. Therefore, I need to load and analyze them on the load_ page () and display the controls. The problem is that the xml files are quite large and time consuming. Therefore, I want to download xml files using the webclient.DownloadFileAsync () method and show information about how many bytes are loaded.

I wrote the code for downloading files, but I donโ€™t know how to update the page on the DownloadProgressChanged event.I think this requires ajax methods.Kindly guide me how to do this.

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> 

Code for (thanks to another stack question)

 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); } } 
+4
source share

Source: https://habr.com/ru/post/1383051/


All Articles