萬盛學電腦網

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

ASP.NET 整合 jQuery Uploadify 實作多檔案上傳與進度條

Uploadify 是經典的 jQuery + Flash 上傳外掛,支援多檔、進度條、拖曳、自動/手動上傳。本文示範在 Web Forms 中動態傳遞額外表單參數 (如 TaskID、使用者 ID) 至後端 Handler。

前端頁面完整代碼

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Upload.aspx.cs" Inherits="Demo.Upload" %>
<!DOCTYPE html>
<html>
<head runat="server">
    <title>Uploadify 多檔上傳示範</title>
    <link href="uploadify/uploadify.css" rel="stylesheet" />
    <script src="uploadify/jquery-1.7.2.min.js"></script>
    <script src="uploadify/swfobject.js"></script>
    <script src="uploadify/jquery.uploadify.min.js"></script>
    <script>
        $(function () {
            var taskId = '<%= TaskID %>';
            var activityId = '<%= ActivityId %>';
            var userId = '<%= CurrentUser.Id %>';

            $('#<%=FileUpload1.ClientID%>').uploadify({
                swf: 'uploadify/uploadify.swf',
                uploader: 'UploadHandler.ashx',
                auto: false,              // 手動觸發上傳
                method: 'post',
                multi: true,
                buttonText: '瀏覽...',
                buttonImage: 'uploadify/browse.png',
                fileTypeDesc: '附件',
                fileTypeExts: '*.pdf;*.doc;*.xls;*.jpg;*.png',
                formData: {               // 靜態參數
                    taskId: taskId,
                    activityId: activityId,
                    userId: userId
                },
                onUploadStart: function (file) {
                    // 動態更新參數 (如下拉選單值)
                    $('#<%=FileUpload1.ClientID%>').uploadify('settings', 'formData', {
                        taskId: taskId,
                        activityId: activityId,
                        userId: userId,
                        secLevel: $('#<%=ddlSecLevel.ClientID%>').val()
                    });
                },
                onUploadSuccess: function (file, data, response) {
                    console.log(file.name + ' 上傳完成:' + data);
                },
                onUploadError: function (file, errorCode, errorMsg) {
                    alert('上傳失敗:' + errorMsg);
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:DropDownList ID="ddlSecLevel" runat="server">
            <asp:ListItem Text="公開" Value="1" />
            <asp:ListItem Text="機密" Value="2" />
        </asp:DropDownList>
        <a href="javascript:$('#<%=FileUpload1.ClientID%>').uploadify('upload','*')">開始上傳</a>
        <a href="javascript:$('#<%=FileUpload1.ClientID%>').uploadify('cancel','*')">取消全部</a>
    </form>
</body>
</html>

後端 Handler (UploadHandler.ashx)

public class UploadHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        try
        {
            HttpPostedFile file = context.Request.Files["Filedata"]; // Uploadify 固定欄位名
            if (file != null && file.ContentLength > 0)
            {
                string taskId = context.Request["taskId"];
                string secLevel = context.Request["secLevel"];
                // ... 驗證、儲存檔案、寫入資料庫 ...
                string savePath = Server.MapPath($"~/Uploads/{taskId}/{Guid.NewGuid()}{Path.GetExtension(file.FileName)}");
                Directory.CreateDirectory(Path.GetDirectoryName(savePath));
                file.SaveAs(savePath);
                context.Response.Write("OK|" + savePath);
            }
            else context.Response.Write("ERROR|無檔案");
        }
        catch (Exception ex)
        {
            context.Response.Write("ERROR|" + ex.Message);
        }
    }
    public bool IsReusable => false;
}

重要遷移提醒

Uploadify 依賴 Flash Player,Adobe 已於 2020/12/31 停止支援 Flash,現代瀏覽器均已移除。
新專案請改用 HTML5 原生方案:
  • Blueimp jQuery File Upload (純 JS、支援分塊、拖曳、進度)
  • Fine Uploader (商業支援、功能完整)
  • Uppy (模組化、React/Vue 友善、支援 Tus 斷點續傳)
  • ASP.NET Core 內建 IFormFile + MultipartBodyLengthLimit 配合前端 fetch/axios 即可輕鬆實作。
copyright © 萬盛學電腦網 all rights reserved