网页.aspx文件中具有百分比的进度条

本文关键字:百分比 aspx 文件 网页 | 更新日期: 2023-09-27 18:21:17

我想制作下载文件的进度条,并更改运行时间百分比

我有代码,但运行时它不会改变进度条的值

则下载完成,进度条直接进入100%。

请给我推荐她的代码是我的示例代码。

private void DownloadFile(string url)
{
    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;
}
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 = "test";
    //prg.Percentage = Convert.ToInt32(percentage);
    prg.Percentage = int.Parse(Math.Truncate(percentage).ToString());
}
protected void Button1_Click(object sender, EventArgs e)
{
    DownloadFile(Sample URL);
}

网页.aspx文件中具有百分比的进度条

使用ASP.NET,在返回客户端之前,像这样的服务器端代码会在页面请求中在服务器上完全求值。您的进度条将直接转到100%,因为在您看到页面上的任何内容之前,传输已完成100%。

在调试器中添加一些日志记录或添加一个断点来设置百分比,通过足够大/足够慢的传输,您将看到进度得到了正确更新。你在浏览器中看不到它,因为在这种情况下,客户端没有运行任何程序来更新浏览器。浏览器渲染只有在完成文件传输之后才会发生,因此设置为100%。

我建议你复习一下ASP.NET页面的生命周期,这样你就能更好地理解为什么会发生这种情况。Button1_Click是一个回发事件,因此它在页面呈现之前进行处理。

为了在传输过程中看到进度更新,您需要使用AJAX的更复杂的策略。有几种不同的方法可以在ASP.NET中实现这一点。

下面是微软使用UpdatePanel的一个例子:

http://msdn.microsoft.com/en-us/library/vstudio/bb386421(v=vs.100).aspx

下面是另一个使用jquery在较低级别执行此操作的示例:

http://www.asp.net/ajaxlibrary/jquery_ui_mvc_progressbar.ashx

我相信你的问题就在这里:

double percentage = bytesIn / totalBytes * 100

应该是:

 double percentage = (bytesIn / totalBytes) * 100

第一部分总是积分部分=0

这意味着:

Math.Truncate(bytesIn / totalBytes * 100) 

将获得0