萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

應用 Response.Write 實現多檔上傳即時進度條

核心原理

利用 Response.Write + Response.Flush 在 ASP.NET 頁面生命週期中,**即時推送** HTML/Script 到瀏覽器,無需 WebSocket 或 Flash,相容 IE8+。

頁面佈局

初始佈局

上傳開始後動態產生進度列:

上傳進度

主流程圖

流程圖

關鍵程式碼

1. 繪製初始進度條 (0%)

public void CreateProgress(HttpFileCollection fileCollection)
{
    var sb = new StringBuilder();
    sb.Append("<html><head></head><body>");
    sb.Append("<script src='FilesUpload.js'></script><table id='mainTable' border='0'>");

    for (int i = 0; i < fileCollection.Count; i++)
    {
        string barId = "progressBar" + i;
        string pctId = "percentage" + i;
        string fileName = fileCollection[i].FileName;
        sb.Append("<tr><td>");
        sb.Append("<p style='float:left;margin-right:10px;'>" + fileName + "</p>");
        sb.Append("<div style='background:white;width:100px;height:12px;border:1px solid black;float:left;margin-right:10px'>");
        sb.Append("<div style='background:green;height:12px;' id='" + barId + "'></div></div>");
        sb.Append("<p style='float:left;margin-right:10px;'><div id='" + pctId + "'></div></p>");
        sb.Append("</td></tr>");
    }
    sb.Append("</table>");

    for (int i = 0; i < fileCollection.Count; i++)
        sb.Append("<script>SetProgressBarProgressAmount(" + i + ", 0);</script>");

    sb.Append("</body></html>");
    HttpContext.Current.Response.Write(sb.ToString());
    HttpContext.Current.Response.Flush(); // 關鍵:強制輸出
}

2. 即時更新進度

public static void SetProgressBar(int id, string progressAmount)
{
    var sb = new StringBuilder();
    sb.Append("<body><script>SetProgressBarProgressAmount(" + id + ", '" + progressAmount + "');</script></body>");
    HttpContext.Current.Response.Write(sb.ToString());
    HttpContext.Current.Response.Flush();
}

3. 檔案讀取迴圈中呼叫更新

int bufferSize = 10000;
byte[] buffer = new byte[bufferSize];
long totalUploadSize = stream.Length;
long totalDownloadedSize = 0;
int tripDownloadSize;

while ((tripDownloadSize = stream.Read(buffer, 0, bufferSize)) > 0)
{
    fs.Write(buffer, 0, tripDownloadSize);
    totalDownloadedSize += tripDownloadSize;
    int percentage = (int)(totalDownloadedSize * 100 / totalUploadSize);
    SetProgressBar(fileIndex, percentage.ToString());
    Thread.Sleep(100); // 降低頻率,避免瀏覽器卡頓
}

架構關鍵:IFrame 隔離

將 `` 放在獨立頁面,主頁以 `