首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET 檔案上傳進度條實作:多風格示範與核心代碼解析

     編輯:ASP.NET 基礎

一、效果預覽

四種進度條風格:

二、核心架構:雙頁面協作 + Session 狀態同步

  1. 上傳頁:含隱藏 <iframe name="uploadFrame">,表單 target="uploadFrame" 提交至 Upload.aspx
  2. 接收頁:Upload.aspx 逐塊寫入檔案,即時更新 Session["UploadInfo"] (含已傳位元組、總大小、檔名)
  3. 輪詢:主頁面 setInterval 呼叫 PageMethods.GetUploadStatus() 讀取 Session,更新進度條 UI

三、關鍵代碼片段

1. 主頁面 JavaScript 輪詢邏輯

var intervalID, progressBar = $find('progress');
function onUploadClick() {
    if (!fileUpload.value) return alert('請選擇檔案');
    $get('upload').disabled = true;
    updateMessage('info', '初始化上傳...');
    form.submit(); // 提交至 iframe
    Sys.UI.DomElement.addCssClass($get('uploadFrame'), 'hidden');
    progressBar.set_percentage(0); progressBar.show();
    intervalID = window.setInterval(function() {
        PageMethods.GetUploadStatus(function(result) {
            if (result) {
                progressBar.set_percentage(result.percentComplete);
                updateMessage('info', result.message);
                if (result.percentComplete == 100) window.clearInterval(intervalID);
            }
        });
    }, 500);
}

2. 伺服端狀態查詢 WebMethod

[WebMethod, ScriptMethod]
public static object GetUploadStatus() {
    var info = HttpContext.Current.Session["UploadInfo"] as UploadInfo;
    if (info != null && info.IsReady) {
        int pct = (int)Math.Ceiling((double)info.UploadedLength / info.ContentLength * 100);
        return new { percentComplete = pct, message = $"上傳 {info.FileName} ... {info.UploadedLength} of {info.ContentLength} 位元組" };
    }
    return null;
}

3. Upload.aspx 逐塊寫入與 Session 更新

protected void Page_Load(object sender, EventArgs e) {
    if (!IsPostBack) return;
    var info = Session["UploadInfo"] as UploadInfo;
    if (info == null) { /* 錯誤處理 */ return; }
    info.IsReady = false;
    if (fileUpload.PostedFile != null && fileUpload.PostedFile.ContentLength > 0) {
        string path = Server.MapPath(@"Uploads");
        string name = Path.GetFileName(fileUpload.PostedFile.FileName);
        info.ContentLength = fileUpload.PostedFile.ContentLength;
        info.FileName = name; info.UploadedLength = 0;
        info.IsReady = true;
        int bufferSize = 10000; // 10KB 緩衝
        byte[] buffer = new byte[bufferSize];
        using (FileStream fs = new FileStream(Path.Combine(path, name), FileMode.Create)) {
            Stream input = fileUpload.PostedFile.InputStream;
            int read;
            while ((read = input.Read(buffer, 0, bufferSize)) > 0) {
                fs.Write(buffer, 0, read);
                info.UploadedLength += read;
                Session["UploadInfo"] = info; // 關鍵:每塊寫入後更新 Session
                Thread.Sleep(100); // 測試用減速,正式環境移除
            }
        }
        File.Delete(Path.Combine(path, name)); // 示範刪除
        ScriptManager.RegisterStartupScript(this, GetType(), "done",
            $"window.parent.onComplete('success', '{name} 已成功上傳');", true);
    }
    info.IsReady = false;
}

四、完整原始碼下載

完整專案含多種進度條樣式 (MattBerseth AJAX 控制項),下載連結:https://xiazai.jb51.net/201509/yuanma/asp_net_progressbar(jb51.net).rar

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved