萬盛學電腦網

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

ASP.NET 檔案無縫上傳:SWFUpload 與 Uploadify 完整實作

前言

傳統 <input type=file> 需整頁回傳,體驗不佳。本文介紹兩款成熟 Flash/jQuery 外掛實現「無刷新、進度條、多檔隊列」上傳。

方案一:SWFUpload

關鍵步驟

  1. 引用 swfupload.js、handlers.js
  2. 頁面初始化設定(按鈕圖片、檔案類型、大小限制、上傳處理程式 URL)
  3. 修改 handlers.js 中 uploadSuccess 事件處理伺服器回傳資料

SWFUpload 初始化設定

SWFUpload 事件綁定

uploadSuccess 事件處理

方案二:Uploadify (jQuery)

關鍵步驟

  1. 引用 jquery.uploadify.js、uploadify.css、uploadify.swf、uploadify-cancel.png
  2. 修正 CSS 中圖片路徑
  3. 初始化設定 uploader(ASHX 處理程式)、fileTypeExts、onUploadSuccess 回呼

Uploadify 初始化

伺服器端處理程式 (UploadFileHandler.ashx)

public class UploadFileHandler : IHttpHandler, IRequiresSessionState
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        // 權限驗證
        if (context.Session["User"] == null)
        {
            context.Response.Write("noPermission");
            context.Response.End();
            return;
        }
        try
        {
            HttpPostedFile file = context.Request.Files["Filedata"]; // 對應 Uploadify 預設
            string ext = Path.GetExtension(file.FileName).ToLower();
            if (!FileTypes.IsAllowed(ext)) return;

            string timeStr = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string virtualPath = "/Upload/" + timeStr + ext;
            string physicalPath = context.Server.MapPath("~/" + virtualPath);
            file.SaveAs(physicalPath);
            context.Response.Write(virtualPath); // 回傳虛擬路徑供前端顯示
        }
        catch (Exception ex)
        {
            context.Response.Write("Error");
            new Common.LogHelper(typeof(UploadFileHandler)).Error(ex);
        }
    }
    public bool IsReusable { get { return false; } }
}

public static class FileTypes
{
    private static List<string> allowed = new List<string>();
    private static string jsonPath = Common.PathHelper.MapPath("~/AllowedFileTypes.json");
    public static List<string> AllowedFileTypes { get { return allowed; } set { allowed = value; } }
    public static bool IsAllowed(string ext) { /* 讀取 JSON 判斷 */ return true; }
}

前端回呼處理

function OnFileUploadSuccess(file, data, response) {
    if (data == 'noPermission') { alert('無上傳權限'); return; }
    if (data == 'Error') { alert('上傳失敗'); return; }
    if (response) {
        alert('上傳成功!');
        $("#filePath").val(data); // 將回傳路徑填入隱藏欄位
    }
}

選型建議

特性SWFUploadUploadify
相依性純 JS + FlashjQuery + Flash
UI 自訂較複雜CSS 易客製化
事件模型手動綁定jQuery 風格回呼
維護狀態停止更新停止更新
現代專案建議改用 HTML5 <input type=file multiple> + FormData + XMLHttpRequest/fetch,或成熟元件如 Fine Uploader、DropzoneJS、Uppy,完全脫離 Flash。
copyright © 萬盛學電腦網 all rights reserved