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

ASP.NET 單檔上傳進度條:jQuery + Cache + GUID 完整方案

     編輯:ASP.NET 基礎

一、系統架構

  • 前端:index.htm (jQuery + jQuery UI),含隱藏 iframe 接收回應
  • 上傳處理:UploadHandler/Default.aspx,依 GUID 寫入檔案並更新 Cache[GUID]
  • 進度查詢:ProgressHandler/Handler.ashx,依 GUID 讀取 Cache 回傳 XML 進度資訊
  • 取消上傳:ProgressHandler/Abort.ashx,設定 Cache 物件 Abort=true
  • GUID 產生:ProgressHandler/GenerateGuid.ashx

二、核心實作細節

1. GUID 產生器

public void ProcessRequest(HttpContext context) {
    context.Response.ContentType = "application/xml";
    var guid = Guid.NewGuid().ToString();
    var doc = new XDocument(new XElement("root", new XElement("guid", guid)));
    context.Response.Write(doc.ToString());
}

2. 上傳處理器

public class UploadUtil {
    private const int BufferSize = 10000;
    private readonly string _filePath;
    private readonly Page _page;
    private readonly string _guid;
    public UploadUtil(Page page, string guid) { _page = page; _guid = guid; 
        _filePath = page.Server.MapPath(ConfigurationManager.AppSettings["upload_folder"]); }
    
    public void Upload() {
        if (_page.Request.Files.Count > 0) DoUpload(_page.Request.Files[0]);
    }
    private void DoUpload(HttpPostedFile file) {
        string dir = _filePath + DateTime.Now.ToFileTime() + "//";
        Directory.CreateDirectory(dir);
        var info = new DownloadingFileInfo(file.FileName, file.ContentLength, file.ContentType);
        HttpContext.Current.Cache[_guid] = info;
        DateTime start = DateTime.Now;
        using (FileStream fs = new FileStream(dir + file.FileName, FileMode.Create))
        using (Stream reader = file.InputStream) {
            byte[] buffer = new byte[BufferSize];
            int len;
            while ((len = reader.Read(buffer, 0, BufferSize)) > 0) {
                fs.Write(buffer, 0, len);
                info.FileFinished += len;
                info.CostTime = (long)(DateTime.Now - start).TotalMilliseconds;
                HttpContext.Current.Cache[_guid] = info;
                if (info.Abort) break;
                Thread.Sleep(1000); // 測試減速
            }
        }
        if (info.Abort && File.Exists(dir + file.FileName)) File.Delete(dir + file.FileName);
    }
}

3. 進度查詢 Handler

public void ProcessRequest(HttpContext context) {
    context.Response.ContentType = "application/xml";
    var guid = context.Request.Form["guid"];
    var info = context.Cache[guid] as DownloadingFileInfo;
    var root = new XElement("root");
    if (info != null) {
        root.Add(new XElement("fileName", info.FileName),
                 new XElement("fileFinished", info.FileFinished),
                 new XElement("fileSize", info.FileSize),
                 new XElement("costTime", info.CostTime),
                 new XElement("fileState", info.FileState),
                 new XElement("speed", info.Speed),
                 new XElement("percent", info.Percent),
                 new XElement("abort", info.Abort));
        if (info.Abort || info.FileState == "finished") context.Cache.Remove(guid);
    } else { root.Add(new XElement("none", "no file")); }
    context.Response.Write(new XDocument(root).ToString());
}

4. 前端 jQuery 輪詢與 UI 更新

$("form").submit(function() {
    _guid = $("#guid").val();
    if (!$("input[name='upload_file']").val()) return alert("未指定檔案"), false;
    _timer = window.setInterval(function() {
        $.ajax({ url: _progress_url, data: { guid: _guid }, dataType: "xml", type: "post",
            success: function(xml) {
                if ($(xml).find("abort").text() == "true") { clearInterval(_timer); return; }
                var pct = parseFloat($(xml).find("percent").text()) * 100;
                $("#upload_progress").css("width", pct + "%");
                $("#finished_percent").html("完成百分比:" + pct.toFixed(2) + "%");
                // 速度、大小、耗時格式化顯示略...
                if (pct >= 100) { clearInterval(_timer); $("#finished_percent").html("上傳完成"); }
            }
        });
    }, 1000);
});

三、特色總結

  • 純 ASP.NET + jQuery 實現,無 Flash、無第三方上傳元件
  • Cache 取代 Session,避免 Session 鎖定導致並發阻塞
  • GUID 隔離多使用者並發上傳
  • 支援取消上傳與檔案自動清理

原始碼下載:https://xiazai.jb51.net/201509/yuanma/asp_net_progressbar(jb51.net).rar

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