多文件非同步上傳帶進度條

来源:http://www.cnblogs.com/kejin123/archive/2016/08/16/5776330.html
-Advertisement-
Play Games

使用: 圖片: ...




///作者:柯錦
///完成時間:2016.08.16
///多文件非同步上傳帶進度條
(function ($) {

    function bytesToSize(bytes) {
        if (bytes === 0) return '0 B';
        var k = 1024, // or 1000
            sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
            i = Math.floor(Math.log(bytes) / Math.log(k));
        return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
    }

    function changeCursor(obj) {
        obj.style.cursor = 'pointer'
    }

    function deleteSelfAndFile(obj) {
        var that = $(obj);
        var parentLi = that.parent("li");
        that.remove();
        parentLi.remove();
    }

    function CreateXMLHttpRequest(target) {
        var xhr = new XMLHttpRequest();
        //var ops = $.data(target, "KJajaxUpload").Options;

        //var v, h, evs = { loadstart: 0, loadend: 0, progress: 0, load: 0, error: 0, abort: 0 };
        //for (v in evs) {
        //    if (h = ops['on' + v]) {
        //        xhr.upload.addEventListener(v, h, false);
        //    }
        //}
        return xhr;
    }

    function InitFileDiv(target, options) {
        var _that = $(target);
        var width = _that.width();
        var hasUploadedDiv = $("<div class='KJajaxUpload_HasUploaded'/>");
        hasUploadedDiv.css({
            width: "100%"
        });
        _that.append(hasUploadedDiv);//
        var divClear = $("<div style='clear:both;'></div>");
        var divUploadBody = $("<div class='KJajaxUpload_Body'/>");
        var divLeft = $("<div class='KJajaxUpload_Left'/>");
        var divRight = $("<div class='KJajaxUpload_Right'/>");
        var uploadButton = $("<input type='button' class='KJajaxUpload_Button' value='Select File'  />");
        if (options.Text) {
            uploadButton.val(options.Text);
        }
        uploadButton.click(function () {
            SelectFiles(target);
        })
        uploadButton.css({
            width: 80
        })
        if (options.Available) {
            uploadButton.prop("disabled", false);
        } else {
            uploadButton.prop("disabled", true);
        }

        divUploadBody.css({
            "overflow": "hidden"
        })
        divLeft.css({
            float: "left",
            width: "100%"
        })
        divRight.css({
            float: "left",
            "margin-left": " -20px"
        })
        _that.append(divClear);
        divLeft.append(uploadButton);// 左 button
        divLeft.append("<font style='font-size:12px;color:red;margin-left:2px;'>可多選</font>")
        divUploadBody.append(divLeft);//
        divUploadBody.append(divRight);// 右 文件列表
        _that.append(divUploadBody);
        return _that;
    }

    /// 創建蒙版
    function CreateMark(target) {
        var mark;
        var width = $(document.body).width() / 2 - 200;
        mark = $("<div>");
        mark.css({
            width: "100%",
            height: "100%",
            position: "fixed",
            left: 0,
            top: 0,
            opacity: 0.5,
            "z-index": 8,
            "background-color": "#EFEFF2",
            "display": "none"
        });
        var contentText = $("<div class='KJajaxUpload_upload_wrapper'>");
        contentText.html("文件上傳中,請稍後...");
        contentText.css({
            "text-align": "center",
            width: "400px",
            "padding-bottom": "50px",
            "z-index": 9,
            position: "fixed",
            left: width + "px",
            "top": "50%",
            "background-color": "white",
            "display": "none"
        })
        contentText.appendTo($("body"));
        mark.appendTo($("body"));
        return mark;
    }
    ///創建進度條
    function CreateUploadBar(target) {
        var contentText = $(".KJajaxUpload_upload_wrapper");
        var fileDiv = $(target);// $.data(target, "KJajaxUpload").FileDiv;
        var FileList = fileDiv.find(".fileuploadlist.newfilelist");
        $.each(FileList, function (i) {
            var fileName = $(this).attr("filename");
            var divid = $(this).attr("id");
            var proressDiv = $("<div id='KJajaxUpload_progress_" + i + "' />");
            var fileNameLable = $("<span >" + fileName + "</span>");
            var barDiv = $("<div id='KJajaxUpload_bar_" + divid + "' name='KJajaxUpload_bar_" + fileName + "'/>");
            barDiv.css({
                width: "350px",
                "margin-left": "20px",
                height: "22px",
                border: "1px solid black ",
                "line-height": "22px"
            })
            var barText1 = $("<div class='KJajaxUpload_progresstext'/>");
            barText1.css({
                "text-align": "center",
                "position": "absolute",
                width: "350px"
            });
            barText1.html("0%");
            var barText2 = $("<div class='KJajaxUpload_progresstext'/>");
            barText2.css({
                "text-align": "center",
                width: "350px",
                "background-color": "#ffe48d"
            });
            barText2.html("0%");

            var barValue = $("<div class='KJajaxUpload_progressvalue'>");
            barValue.css({
                position: "relative",
                overflow: "hidden",
                width: "0px"
            })
            barValue.append(barText2);
            barDiv.append(barText1);
            barDiv.append(barValue);
            proressDiv.append(fileNameLable);
            contentText.append(proressDiv);
            contentText.append(barDiv);
        });
    }

    function ChangeProcess(filename, evt) {
        var loaded = evt.loaded;     //已經上傳大小情況 
        var tot = evt.total;      //附件總大小 
        var per = Math.floor(100 * loaded / tot);  //已經上傳的百分比 
        var that = $("[name='KJajaxUpload_bar_" + filename + "']");
        that.find('div.KJajaxUpload_progressvalue').css("width", per + "%");
        that.find('div.KJajaxUpload_progresstext').html(per + "%");
    }

    ///選擇文件
    function SelectFiles(target) {
        var options = $.data(target, "KJajaxUpload").Options;
        var deleteButtonUrl = options.deleteButtonUrl;
        var ele = $("<input type='file'/>");
        ele.prop("multiple", options.multiple !== false);
        ele.hide();
        ele.change(function (e) {
            var exist = false;
            var files = e.target.files;
            var filenames = GetalreadyExistFileNames(target);
            for (var item in files) {
                var file = files[item];
                if ($.inArray(file.name, filenames) > -1) {
                    exist = true;
                    break;
                }
            }
            if (!exist) {
                var ul = $("<ul style='margin:0px;'/>");
                for (var i = 0, n = files.length; i < n; i++) {
                    var deletebutton = $("<img src='" + deleteButtonUrl + "' onmouseover='changeCursor(this)' class='deleteBtn' />");
                    deletebutton.click(function () {
                        deleteSelfAndFile(this);
                    })
                    var guid = new GUID().New();
                    var li = $('<li class="fileuploadlist newfilelist" id="' + guid + '" filename="' + files[i].name + '" >' + files[i].name + ' (' + bytesToSize(files[i].size) + ' )</li>');
                    li.append(deletebutton);
                    ul.append(li);
                }
                $(target).find(".KJajaxUpload_Right").append(ul);
                options.onChange.call(this, e);
            } else {
                alert("文件名重覆");
                ele.remove();
                return
            }

        });
        $(target).append(ele);
        ele.click();
    }

    /// 獲取已經存在的文件名列表
    function GetalreadyExistFileNames(target) {
        var that = $(target);
        var fileExists = that.find(".fileuploadlist");
        var fileNames = [];
        /// 還存在的文件列表
        fileExists.each(function () {
            var filename = $(this).attr("filename");
            if ($.inArray(filename, fileNames) == -1) {
                fileNames.push(filename);
            }
        })
        return fileNames;
    }

    /// 上傳文件
    function UploadFiles(target) {
        var that = $(target);
        var fileInputs = that.find(":file");
        var options = $.data(target, "KJajaxUpload").Options;
        var deleteButtonUrl = options.deleteButtonUrl;
        var onUploaded = options.onUploaded;
        if (fileInputs.length > 0) {
            var total = 0;
            var uploaded = 0;
            var reponses = [];
            var mark = $.data(target, "KJajaxUpload").Mark;
            var markcontent = $(".KJajaxUpload_upload_wrapper");
            mark.show();
            markcontent.show();
            CreateUploadBar(target);

            var fileExists = that.find(".fileuploadlist");
            var fileNames = [];
            /// 還存在的文件列表
            fileExists.each(function () {
                var filename = $(this).attr("filename");
                if ($.inArray(filename, fileNames) == -1) {
                    fileNames.push(filename);
                }
            })

            for (var i = 0; i < fileInputs.length; i++) {
                var fileinput = fileInputs[i];
                var files = fileinput.files;

                if (files.length > 0) {
                    for (var j = 0, n = files.length; j < n; j++) {
                        if ($.inArray(files[j].name, fileNames) > -1) {
                            total++;
                            var filename = files[j].name;
                            var paramData = options.formData;

                            var data = new FormData();
                            data.append("uploadedfile[" + j + "]", files[j]);
                            if (paramData != null) {
                                for (var k in paramData) {
                                    data.append(k, paramData[k]);
                                }
                            }
                            var xhr = CreateXMLHttpRequest(target);
                            xhr.upload.addEventListener("progress",
                                function (data) {
                                    return function (e) {
                                        ChangeProcess(data, e);
                                    }
                                }(filename), false);
                            xhr.upload.addEventListener("loadend", function () {
                            }, false);
                            xhr.upload.addEventListener("load", function () {
                                uploaded++;
                            }, false);
                            xhr.onreadystatechange = function () {
                                if (this.readyState == 4) {// 4 = "loaded"
                                    if (this.status == 200) {// 200 = OK                                   
                                        reponses.push(this.responseText);
                                        if (uploaded == $.data(target, "KJajaxUpload").TotalFiles) {

                                            var HasUploaded = that.find(".KJajaxUpload_HasUploaded");

                                            var ul = $("<ul style='margin:0px;'/>");

                                            for (var t = 0; t < reponses.length; t++) {
                                                var files = JSON.parse(reponses[t]);
                                                for (var i = 0, n = files.length; i < n; i++) {
                                                    var deletebutton = $("<img src='" + deleteButtonUrl + "' onmouseover='changeCursor(this)' class='deleteBtn' />");
                                                    deletebutton.click(function () {
                                                        deleteSelfAndFile(this);
                                                    })
                                                    var guid = new GUID().New();
                                                    var li = $('<li class="fileuploadlist" id="' + guid + '" filename="' + files[i].Name + '"  filepath="' + files[i].FilePath + '" ><a  target="_blank" href="' + files[i].FileUrl + '">' + files[i].Name + '</a>  </li>');
                                                    li.append(deletebutton);
                                                    ul.append(li);
                                                }
                                            }
                                            that.find(".KJajaxUpload_Right").empty();
                                            HasUploaded.append(ul);
                                            fileInputs.remove();
                                            Uploaded(target);
                                            var data = GetAlreadyUploadedFiles(target);
                                            onUploaded.call(null, data);
                                        }
                                    }
                                    else {
                                        alert("Problem retrieving XML data");
                                    }
                                }
                            };

                            xhr.open("POST", options.url, true);
                            xhr.send(data);
                        }
                    }
                    var state = $.data(target, "KJajaxUpload");
                    state.TotalFiles = total;
                    $.data(this, "KJajaxUpload", state);

                }

            }
        } else {
            var data = GetAlreadyUploadedFiles(target);
            onUploaded.call(null, data);
        }
        return that;
    }

    /// 上傳完畢
    function Uploaded(target) {
        alert("文件上傳完畢");
        var mark = $.data(target, "KJajaxUpload").Mark;
        var markcontent = $(".KJajaxUpload_upload_wrapper");
        mark.hide();
        markcontent.hide();
        var that = $(target);
        var fileInputs = that.find(":file");
        fileInputs.remove();
    }

    ///初始化已有的數據
    function AlreadFiles(target, options) {
        var that = $(target);
        var deleteButtonUrl = options.deleteButtonUrl;
        var files = options.AlreadFiles;

        var HasUploaded = that.find(".KJajaxUpload_HasUploaded");

        if (files.length > 0) {
            var ul = $("<ul style='margin:0px;'/>");

            for (var i = 0, n = files.length; i < n; i++) {
                var deletebutton = $("<img src='" + deleteButtonUrl + "' onmouseover='changeCursor(this)' class='deleteBtn' />");
                deletebutton.click(function () {
                    deleteSelfAndFile(this);
                })

                var pos = files[i].lastIndexOf("\\");
                var filepos = files[i].lastIndexOf("uploadFile");
                var reg = /[\\\/]/g;
                var filePath = files[i];
                var fileUrl = files[i].substr(filepos).replace(reg, '/');
                var fileName = files[i].substr(pos + 1);
                fileName = fileName.substr(fileName.lastIndexOf("_S_") + 3);
                var guid = new GUID().New();
                var li = $('<li class="fileuploadlist" id="' + guid + '" filename="' + fileName + '"  filepath="' + filePath + '" ><a  target="_blank" href="' + fileUrl + '">' + fileName + '</a>  </li>');
                li.append(deletebutton);
                ul.append(li);
            }
            HasUploaded.append(ul);
        }

    }


    function GetAlreadyUploadedFiles(target) {
        var that = $(target);
        var HasUploaded = that.find(".KJajaxUpload_HasUploaded li");
        var datas = [];
        HasUploaded.each(function () {
            var data = {};
            data.name = $(this).attr("filename");
            data.filepath = $(this).attr("filepath");
            data.fileurl = $(this).find("a").attr("href");
            datas.push(data);
        })

        return datas;
    }


    $.fn.KJajaxUpload = function (options, param) {
        var that = this;
        if (typeof options == "string") {
            var method = $.fn.KJajaxUpload.Methods[options];
            if (method) {
                return method(this, param);
            }
        }
        options = options || {};

        return this.each(function () {

            var that = this;
            var state = $.data(this, "KJajaxUpload");
            if (state) {
                $.extend(state.Options, options);
            } else {
                var _options = $.extend({}, $.fn.KJajaxUpload.Default, options);
                InitFileDiv(this, _options);
                AlreadFiles(this, _options);
                state = $.data(this, "KJajaxUpload", {
                    Options: _options,
                    Mark: CreateMark(this),
                    TotalFiles: 0
                });
            }
        })
    }
    $.fn.KJajaxUpload.Default = {
        url: '/Ashx/UploadFilesHandler.ashx?r=' + Math.random(),
        formData: {},//要傳遞的參數
        Text: "選擇文件",
        ContinueAddText: "繼續添加",
        multiple: true,
        AlreadFiles: [],// 初始化已經存在的文件
        Available: true,// 可用的
        deleteButtonUrl: '/Style/images/delete.jpg',
        onInit: function () { },
        onChange: function () { },
        onUploaded: function () { }// 文件上傳完畢後的回調函數
    };
    $.fn.KJajaxUpload.Methods = {
        options: function (jq) {
            return $.data(jq[0], "KJajaxUpload").Options;
        },
        upload: function (jq) {
            return UploadFiles(jq[0]);
        }
    };

})(jQuery)

 




後端代碼
/// <summary>
    /// UploadFilesHandler 的摘要說明
    /// </summary>
    public class UploadFilesHandler : IHttpHandler
    {



        public void ProcessRequest(HttpContext context)
        {
            List<FileReponse> list = new List<FileReponse>();

            string filePath = System.AppDomain.CurrentDomain.BaseDirectory.ToString() + @"uploadFile\" + DateTime.Now.Year.ToString() + @"\" + DateTime.Now.Month.ToString() + @"\" + DateTime.Now.Day.ToString() + @"\" + System.Web.HttpUtility.UrlDecode(context.Request.Params["userName"].ToString()) + @"\";


            if (context.Request.Files.Count > 0)
            {
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                try
                {


                    foreach (string files in context.Request.Files)
                    {
                        HttpPostedFile upfile = context.Request.Files[files];
                        int bufferSize = 1024 * 50;//50K

                        string _guid = Guid.NewGuid().ToString().Replace("-", "");

                        byte[] buffer = new byte[bufferSize];
                        int currentCounts = 0;//
                        long totalLength = upfile.ContentLength;
                        string name = upfile.FileName.Substring(upfile.FileName.LastIndexOf("\\") + 1);
                        string fileName = filePath + _guid + "_S_" + name;
                        using (FileStream fs = new FileStream(fileName, FileMode.Create))
                        {
                            while (currentCounts < totalLength)
                            {
                                int bytes = upfile.InputStream.Read(buffer, 0, bufferSize);
                                fs.Write(buffer, 0, bytes);
                                //Thread.Sleep(1);//0.001s
                                currentCounts += bytes;
                            }
                        }
                        FileReponse item = new FileReponse();
                        item.Name = name;
                        item.FilePath = fileName;
                        int filepos = item.FilePath.LastIndexOf("uploadFile");
                        item.FileUrl = item.FilePath.Substring(filepos);

                        list.Add(item);
                    }



                }
                catch (Exception ex)
                {

                }
            }

            string reponse = JsonConvert.SerializeObject(list);
            context.Response.Write(reponse);

            //context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }


    internal class FileReponse
    {
        public string Name { get; set; }
        public string FilePath { get; set; }
        public string FileUrl { get; set; }
    }



使用:

var config = {};
        config.formData = formData;
        if (!HasTheRight("HDComplaintsArea")) {
            config.Available = false;
        }
       if (record.Attachments) {
                config.AlreadFiles = record.Attachments;
            }
        config.onUploaded = function (data) {
            save(data);
        }
        $("#filediv").KJajaxUpload(config);


$("#btnSave").click(function () {
        $("#filediv").KJajaxUpload("upload");
    })

function save(data) {
       fields.Attachments = [];
        for (var i = 0; i < data.length; i++) {
            fields.Attachments.push(data[i].filepath);
        }      
        fields.Attachments = JSON.stringify(fields.Attachments);
}

 

圖片:



 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • toggleClass 用來給匹配元素切換類 語法 "參考 http://www.w3schools.com/jquery/html_toggleclass.asp " 但是個人感覺應該是這樣的: 同時指定了classname和function 只有classname生效 參數說明 Paramete ...
  • 在Web項目的開發中,js,css文件會隨著項目的開發變得越來越多,越來越大,這就給給性能方面帶來一些問題,如,頁面引入的的js,css越多的話,那麼對就增加了http請求數,解決該問題的一個好的方法就是合併js,css文件. ...
  • 自己對canvas,但又有一顆做游戲的心TT。然後記錄一下對canvas的學習吧,用一個按方向鍵控制的小圓點來做練習。(編程時用了一些es6的語法) 示例的html很簡單,只有一個canvas元素: 這裡可以看到我在canvas標簽里直接定義了寬和高,這和在css裡面定義是不同的,canvas元素其 ...
  • Array類型是ECMAScript中最常用的引用類型。ECMAScript中的數據與其它大多數語言中的數組有著相當大的區別。雖然ECMAScript中的數據與其它語言中的數組一樣都是數據的有序列表,但不同的是,ECMAScript數組中的每一項可以保存任何類型的數據,無論是數值、字元串或者是對象。 ...
  • 這次的分享,主要還是想跟大家聊聊Javascript語言中很重要的概念之一,對象。為什麼說之一呢?因為Javascript其他重要概念還包括:作用域 作用域鏈 繼承 閉包 函數 繼承 數組 ...... 有機會會跟大家分享這些概念的。以下的介紹會分為如下:1:前言2:概述 2.1:對象創建 2.2: ...
  • 今天我又碼了兩個特效:一個是用原生input[type=range]的,另一個完全自定義的;下麵是完整代碼和演示: <!DOCTYPE html tip{ position: absolute; top: 30px; left: 0; right: 0; width: 200px; height: ...
  • DOM技術實現競賽題頁面 這一段時間學習了DOM操作和JS開發,我就自己開發一個競賽題的頁面。 一、業務需求 1、目標:做一個一百道選擇題的頁面 2、功能: 顯示題目和選項。 下一題上一題的按鈕,到第一題和第一百題時停止。 答對了顯示笑臉和笑話,答錯了顯示苦臉和正確答案。 二、開發思路 採用自頂向下 ...
  • 雖然我們的js將來會被很多的礦街(jQuery)取代,但js,我們現在依然不得不學,因為用途很廣泛 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...