DIV CSS 佈局教程網

ASP.NET MVC 中使用 WebUploader:外掛封裝與後端接收
編輯:JQuery入門技巧     

在雙核心瀏覽器的 Chrome 核心下使用 uploadify 一直有 302 的問題,而且不容易修。之所以偏好 360 瀏覽器,是因為可以為客戶鎖定渲染核心:

 <!-- 預設使用極速核心 -->
<meta name="renderer" content="webkit" />
<!-- 預設使用 IE 相容核心 -->
<meta name="renderer" content="ie-comp" />
<!-- 預設使用 IE 標準核心 -->
<meta name="renderer" content="ie-stand" /> 

要解決 302 問題其實不難,改用 HTML5 上傳即可。正好在 ueditor 裡看到百度的 WebUploader——它會自動在 Flash 與 HTML5 之間選擇,是相當成熟的解決方案。

一、封裝成 jQuery 外掛

先看前端。我把最常用的操作包成外掛。在 ASP.NET 與 MVC 中,建議使用相對應用程式的絕對路徑,自行定義全域變數 applicationPath:

 var applicationPath = "@(Href("~")=="/"?"":Href("~"))"; 

外掛主體:

 (function ($, window) {
    var applicationPath = window.applicationPath === "" ? "" : window.applicationPath || "../..";

    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }

    function initWebUpload(item, options) {
        if (!WebUploader.Uploader.support()) {
            var error = "上傳控件不支持您的瀏覽器!請嘗試升級 flash 版本或使用 Chrome 引擎的瀏覽器。";
            if (window.console) { window.console.log(error); }
            $(item).text(error);
            return;
        }

        var defaults = {
            hiddenInputId: "uploadifyHiddenInputId",
            onAllComplete: function (event) {},   // 所有檔案都上傳後
            onComplete:    function (event) {},   // 每上傳一個檔案
            innerOptions:  {},
            fileNumLimit:  undefined,
            fileSizeLimit: undefined,
            fileSingleSizeLimit: undefined,
            PostbackHold:  false
        };
        var opts = $.extend({}, defaults, options);

        var hdFileData = $("#" + opts.hiddenInputId);
        var target = $(item);

        var pickerid = (typeof guidGenerator36 != 'undefined')
            ? guidGenerator36()
            : (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);

        target.append(
            '<div class="webuploader">' +
            '  <div id="thelist" class="uploader-list"></div>' +
            '  <div class="btns"><div id="' + pickerid + '">選擇檔案</div></div>' +
            '</div>');

        var $list = target.find('#thelist'),
            $btn  = target.find('#ctlBtn'),
            state = 'pending',
            jsonData = { fileList: [] };

        var webuploaderoptions = $.extend({
            swf:    applicationPath + '/Scripts/lib/webuploader/Uploader.swf',
            server: applicationPath + '/MvcPages/WebUploader/Process',
            pick:   '#' + pickerid,
            resize: false,
            fileNumLimit:        opts.fileNumLimit,
            fileSizeLimit:       opts.fileSizeLimit,
            fileSingleSizeLimit: opts.fileSingleSizeLimit
        }, opts.innerOptions);

        var uploader = WebUploader.create(webuploaderoptions);

        // 回發(PostBack)時還原 hidden 欄位中的既有資料
        var fileDataStr = hdFileData.val();
        if (fileDataStr && opts.PostbackHold) {
            jsonData = JSON.parse(fileDataStr);
            $.each(jsonData.fileList, function (index, fileData) {
                var newid = S4();
                fileData.queueId = newid;
                $list.append('<div id="' + newid + '" class="item">' +
                    '<div class="info">' + fileData.name + '</div>' +
                    '<div class="state">已上傳</div>' +
                    '<div class="del"></div></div>');
            });
            hdFileData.val(JSON.stringify(jsonData));
        }

        uploader.on('fileQueued', function (file) {
            $list.append('<div id="' + file.id + '" class="item">' +
                '<div class="info">' + file.name + '</div>' +
                '<div class="state">等待上傳...</div>' +
                '<div class="del"></div></div>');
        });

        uploader.on('uploadProgress', function (file, percentage) {
            var $li = target.find('#' + file.id), $percent = $li.find('.progress .bar');
            if (!$percent.length) {
                $percent = $('<div class="progress"><div class="bar"></div></div>')
                    .appendTo($li).find('.bar');
            }
            $li.find('div.state').text('上傳中');
            $li.find(".text").text(Math.round(percentage * 100) + '%');
            $percent.css('width', percentage * 100 + '%');
        });

        uploader.on('uploadSuccess', function (file, response) {
            target.find('#' + file.id).find('div.state').text('已上傳');
            var fileEvent = {
                queueId: file.id, name: file.name, size: file.size,
                type: file.type, filePath: response.filePath
            };
            jsonData.fileList.push(fileEvent);
            opts.onComplete(fileEvent);
        });

        uploader.on('uploadError', function (file) {
            target.find('#' + file.id).find('div.state').text('上傳出錯');
        });

        uploader.on('uploadComplete', function (file) {
            target.find('#' + file.id).find('.progress').fadeOut();
            $("#" + opts.hiddenInputId).val(JSON.stringify(jsonData));
            opts.onAllComplete(jsonData.fileList);
        });

        uploader.on('fileQueued',   function () { uploader.upload(); });
        uploader.on('filesQueued',  function () { uploader.upload(); });

        uploader.on('all', function (type) {
            if (type === 'startUpload')      state = 'uploading';
            else if (type === 'stopUpload')  state = 'paused';
            else if (type === 'uploadFinished') state = 'done';
            $btn.text(state === 'uploading' ? '暫停上傳' : '開始上傳');
        });

        $btn.on('click', function () {
            if (state === 'uploading') { uploader.stop(); } else { uploader.upload(); }
        });

        // 刪除
        $list.on("click", ".del", function () {
            var $ele = $(this), id = $ele.parent().attr("id"), deletefile = {};
            $.each(jsonData.fileList, function (index, item) {
                if (item && item.queueId === id) {
                    uploader.removeFile(uploader.getFile(id));   // 別漏掉這行
                    deletefile = jsonData.fileList.splice(index, 1)[0];
                    $("#" + opts.hiddenInputId).val(JSON.stringify(jsonData));
                    $.post(applicationPath + "/Webploader/Delete",
                        { 'filepathname': deletefile.filePath }, function () {
                            $ele.parent().remove();
                        });
                    return false;
                }
            });
        });
    }

    $.fn.powerWebUpload = function (options) {
        var ele = this;
        if (typeof PowerJs != 'undefined') {
            $.lazyLoad(applicationPath + "/Scripts/lib/webuploader/webuploader.css", function(){}, 'css');
            $.lazyLoad(applicationPath + "/Scripts/lib/webuploader/webuploader.min.js", function () {
                initWebUpload(ele, options);
            });
        } else {
            initWebUpload(ele, options);
        }
    };
})(jQuery, window); 

頁面引入後,一行就能啟用:

 $("#uploader").powerWebUpload({ hiddenInputId: "uploadhidden" }); 

HTML 端只需要一個容器與一個 hidden 欄位:

 <div id="uploader"></div>
<asp:HiddenField ID="hfFilePath" ClientIDMode="Static" runat="server" /> 

二、MVC 版後端接收

即使是 ASP.NET,只要引入 MVC 做 Ajax 也完全可行:

 using System;
using System.IO;
using System.Web;
using System.Web.Mvc;

public class WebUploaderController : BaseController
{
    static string urlPath = "../../Upload/Document";

    public ActionResult Process(string id, string name, string type,
                               string lastModifiedDate, int size,
                               HttpPostedFileBase file)
    {
        string filePathName = string.Empty;
        string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Upload\\Document");

        if (Request.Files.Count == 0) {
            return Json(new { jsonrpc = 2.0, error = new { code = 102, message = "保存失敗" }, id = "id" });
        }

        try {
            // 在此處理檔案保存,並回傳需要寫進 hidden 欄位的資料
            // 檔案內容在 file 或 Request.Files[0]
            filePathName = /* ... */ string.Empty;
        } catch (Exception) {
            return Json(new { jsonrpc = 2.0, error = new { code = 103, message = "保存失敗" }, id = "id" });
        }

        return Json(new { jsonrpc = "2.0", id = "id", filePath = urlPath + "/" + filePathName });
    }

    public ActionResult Delete(string filePathName)
    {
        if (string.IsNullOrEmpty(filePathName)) { return Content("no"); }

        // 安全檢查:路徑前綴要正確,且不得包含上跳目錄
        if (!filePathName.StartsWith(urlPath) ||
            filePathName.Substring(6, filePathName.Length - 7).Contains("../")) {
            return Content("no!");
        }

        string localFilePathName = this.Server.MapPath(filePathName);
        try {
            bool b = UploadifyManager.DeleteAttachment(localFilePathName);
            if (!b) throw new Exception("刪除檔案失敗");
            return Content("ok");
        } catch {
            return Content("no");
        }
    }
} 

完整可執行的 Demo 放在 GitHub 上:https://github.com/gxrsprite/AspnetMvcWebuploaderDemo。

補充筆記

擴充自訂參數。利用 uploadBeforeSend 事件可以在每次送出前動態加入參數,外掛內依需求調整即可。

Cookie 問題。我使用微軟內建的登入機制,沒有做任何特殊處理就完全正常,不需要額外傳 session id。

路徑安全。Delete 方法中那段前綴與 ../ 檢查是必要的,否則會留下任意檔案刪除的風險。正式環境建議改用 GUID 命名實體檔案、把對應關係存在資料庫,只對外暴露代碼,安全性會更好。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved