百度 flash html5自切換 多檔案非同步上傳控制元件webuploader基本用法

發表於2019-05-11

雙核瀏覽器下在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,就是一個成熟的解決方案了。
 
先看前端,我們將最常用的操作封裝為外掛,asp.net中和MVC中最好使用相對於應用程式的絕對路徑,自行定義全域性applicationPath :var applicationPath = "@(Href("~")=="/"?"":Href("~"))"; 
前端外掛程式碼:
var applicationPath = applicationPath === "" ? "" : applicationPath || "../..";
(function ($, applicationPath) {
    function initWebUpload(item, options) {
        var defaults = {
            hiddenInputId: "uploadifyHiddenInputId", // input hidden id
            onAllComplete: function (event) { }, // 當所有file都上傳後執行的回撥函式
            onComplete: function (event) { },// 每上傳一個file的回撥函式
            innerOptions: {},
            fileNumLimit: undefined,
            fileSizeLimit: undefined,
            fileSingleSizeLimit: undefined
        };
 
        var opts = $.extend({}, defaults, options);
 
        var target = $(item);//容器
        var pickerid = "";
        if (typeof guidGenerator36 != 'undefined')//給一個唯一ID
            pickerid = guidGenerator36();
        else
            pickerid = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
 
        var uploaderStrdiv = '<div class="webuploader">' +
            '<div id="thelist" class="uploader-list"></div>' +
            '<div class="btns">' +
            '<div id="' + pickerid + '">選擇檔案</div>' +
            //'<a id="ctlBtn" class="btn btn-default">開始上傳</a>' +
            '</div>' +
        '</div>';
        target.append(uploaderStrdiv);
 
        var $list = target.find('#thelist'),
             $btn = target.find('#ctlBtn'),//這個留著,以便隨時切換是否要手動上傳
             state = 'pending',
             uploader;
 
        var jsonData = {
            fileList: []
        };
 
        var webuploaderoptions = $.extend({
 
            // swf檔案路徑
            swf: applicationPath + '/Scripts/lib/webuploader/Uploader.swf',
 
            // 檔案接收服務端。
            server: applicationPath + '/MvcPages/WebUploader/Process',
 
            // 選擇檔案的按鈕。可選。
            // 內部根據當前執行是建立,可能是input元素,也可能是flash.
            pick: '#' + pickerid,
 
            // 不壓縮image, 預設如果是jpeg,檔案上傳前會壓縮一把再上傳!
            resize: false,
            fileNumLimit: opts.fileNumLimit,
            fileSizeLimit: opts.fileSizeLimit,
            fileSingleSizeLimit: opts.fileSingleSizeLimit
        },
        opts.innerOptions);
        var uploader = WebUploader.create(webuploaderoptions);
 
        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 = $('<span class="progress">' +
                    '<span  class="percentage"><span class="text"></span>' +
                  '<span class="bar" role="progressbar" style="width: 0%">' +
                  '</span></span>' +
                '</span>').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();
            var fp = $("#" + opts.hiddenInputId);
            fp.val(JSON.stringify(jsonData));
            opts.onAllComplete(jsonData.fileList);
        });
 
        uploader.on('fileQueued', function (file) {
            uploader.upload();
        });
 
        uploader.on('filesQueued', function (file) {
            uploader.upload();
        });
 
        uploader.on('all', function (type) {
            if (type === 'startUpload') {
                state = 'uploading';
            } else if (type === 'stopUpload') {
                state = 'paused';
            } else if (type === 'uploadFinished') {
                state = 'done';
            }
 
            if (state === 'uploading') {
                $btn.text('暫停上傳');
            } else {
                $btn.text('開始上傳');
            }
        });
 
        $btn.on('click', function () {
            if (state === 'uploading') {
                uploader.stop();
            } else {
                uploader.upload();
            }
        });
        //刪除
        $list.on("click", ".del", function () {
            var $ele = $(this);
            var id = $ele.parent().attr("id");
            var deletefile = {};
            $.each(jsonData.fileList, function (index, item) {
                if (item && item.queueId === id) {
                    deletefile = jsonData.fileList.splice(index, 1)[0];
                    $("#" + opts.hiddenInputId).val(JSON.stringify(jsonData));
                    $.post(opts.ashx, { 'type': 'delete', 'filepathname': deletefile.filePath }, function (returndata) {
                        $ele.parent().remove();
                    });
                    return;
                }
            });
        });
 
    }
 
 
    $.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, applicationPath);
頁面引入上述js後使用:
 $("#uploader").powerWebUpload({ hiddenInputId: "uploadhidden" });
html端需要一個容器和hidden
<div id="uploadify" class="shortuploader"></div> <asp:HiddenField ID="hfFilePath" ClientIDMode="Static" runat="server" />

 
MVC版後端檔案接收,即便你是asp.net 引入mvc做ajax也是可以的:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
public class WebUploaderController : BaseController
    {
        public ActionResult Process(string id, string name, string type, string lastModifiedDate, int size)
        {
            string filePathName = string.Empty;
            string urlPath = "../../App_Upload/Document";
            string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, "App_Upload\\Document");
            if (Request.Files.Count == 0)
            {
                return Json(new { jsonrpc = 2.0, error = new { code = 102, message = "儲存失敗" }, id = "id" });
            }
            try
            {
                filePathName = //自己在這裡處理檔案儲存 Request.Files[0]
            }
            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
            });
        }
    }

評論(1)

相關文章