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

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


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(); // 關鍵:強制輸出
}
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();
}
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); // 降低頻率,避免瀏覽器卡頓
}
將 `` 放在獨立頁面,主頁以 `