webuploader分片上傳

屁話很少說直接上主題;css

  1. webuploader,sj(WebUploader 0.1.6)網上有下
  2. powerUpload.js 本身寫的基與樓上的插件
  3. asp.net mvc/Api

   實現效果:html

        HTML:web

<div class="col-sm-5 type_listfile " id="FILELIST">
                <div class="panel panel-default">
                    <div class="panel-heading"> 產品說明書 </div>
                    <div class="panel-body">
                        <ul id="picture-ul-0" class="picture-ul-0">
                        </ul>
                    </div>

                </div>
                <div id="picker" class=" _picker" data-toggle="tooltip">選擇說明書</div>
            </div>

 JavaScript:服務器

var WebUpload = new $WebUpload($("#FILELIST"), '/Controller/Upload', { PF_GUID: ID,DirectoryName:GUID}, $(".picture-ul-0")); var uploader = WebUpload .init();

Controller:併發

public ActionResult Upload(string Id,string DirectoryName) {     var sb = new StringBuilder();   sb.Append("["); string NewFileNmae = Guid.NewGuid().ToString().Replace("-", "").ToUpper(); string fileExt = string.Empty; string FileFileName = string.Empty; if (HttpContext.Request.Form.AllKeys.Any(m => m == "chunk")) { //取得chunk和chunks
        int chunkIndex = Convert.ToInt32(Request.Form["chunk"]);//當前分片在上傳分片中的順序(從0開始)
        int chunkCount = Convert.ToInt32(Request.Form["chunks"]);//總分片數
        string chunkDirectory = FileModelPath + DirectoryName + "/"; string chunkDirectoryIndex = chunkDirectory + chunkIndex.ToString(); if (!Directory.Exists(Server.MapPath(chunkDirectory))) { Directory.CreateDirectory(Server.MapPath(chunkDirectory)); }       FileStream addFile = new FileStream(Server.MapPath(chunkDirectoryIndex), FileMode.Append, FileAccess.Write);       BinaryWriter AddWriter = new BinaryWriter(addFile);       var file = Request.Files[0];       Stream stream = file.InputStream;       BinaryReader TempReader = new BinaryReader(stream);       AddWriter.Write(TempReader.ReadBytes((int)stream.Length));       TempReader.Close();       stream.Close();       AddWriter.Close();       addFile.Close();        Thread.Sleep(200);        if (chunkIndex + 1 == chunkCount) { isChunk = true; fileExt = Request.Files[0].FileName.Substring(Request.Files[0].FileName.LastIndexOf('.')); var files = Directory.GetFiles(Server.MapPath(chunkDirectory)); var finalPath = Path.Combine(FileModelPath, NewFileNmae + fileExt);//最終的文件名
var fs = new FileStream(Server.MapPath(finalPath), FileMode.Create); FileFileName = Request.Files[0].FileName; foreach (var part in files.OrderBy(x => x.Length).ThenBy(x => x))//排一下序,保證從0-N Write
{ var bytes = System.IO.File.ReadAllBytes(part); fs.Write(bytes, 0, bytes.Length); bytes = null; System.IO.File.Delete(part);//刪除分塊
} fs.Flush(); fs.Close(); string str = Server.MapPath(FileModelPath + DirectoryName + "-" + PF_TYPE); if (Directory.Exists(str)) { Directory.Delete(str); } isChunk = false; sb.AppendFormat("{0}\"id\":\"{1}\",\"msge\":\"{2}\"{3},", "{", "PF_NAME", "信息上傳成功", "}"); } else { sb.AppendFormat("{0}\"id\":\"{1}\",\"msge\":\"{2}\"{3},", "{", "PF_NAME", "信息分片上傳中", "}"); } } return AjaxResult(state, sb.ToString(), true); } 

Jquery.插件mvc

(function () { var $WebUpload = function (_uploader, url, fdata, _queueList, _completefun, path, _NumLimit) { this._uploader = _uploader; this.serverurl = url; this.fmDate = fdata; this._imgpath = path; // this.imageExtensions = 'gif,jpg,jpeg,bmp,png';
       // this.mimeTypes = 'image/gif,image/jpg,image/jpeg,image/bmp,image/png';
        // 縮略圖大小
        //this.ratio = window.devicePixelRatio || 1,
          // this.thumbnailWidth = 160 * this.ratio;
        //this.thumbnailHeight = 120 * this.ratio;
        this.fileSizeLimit = 1048576000; this.fileNumLimit = _NumLimit; this.fileSingleSizeLimit = 1048576000; this.swfurl = 'Uploader.swf'; this.custsuccess = null; this.custerror = null; this.fileCount = 0; this._queueList = _queueList; this._completefun = _completefun;//上傳完成後須要執行的函數或者對象的點擊事件
        this.WebUploader; this._messge; }; $WebUpload.prototype = { /** * 初始化webUploader */ init: function () { var uploader = this.create(); this.bindEvent(uploader); return uploader; }, fileNumber: function () { return this.fileCount; }, /** * 建立webuploader對象 */ create: function () { var webUploader = WebUploader.create({ pick: $('._picker', $(this._uploader))[0], accept: { title: 'Files', extensions: 'pdf,doc,docx,xls,xlsx,gif,jpg,jpeg,bmp,png', mimeTypes: 'application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                        + ',application/pdf' 
                        +',application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel'
                        +',image/gif,image/jpg,image/jpeg,image/bmp,image/png' }, //accept: {
                // title: 'Files',
                // extensions: 'pdf,doc,docx,xls,xlsx',
                // mimeTypes: 'application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                // + ',application/pdf' + ',application/vnd.ms-excel,application/vnd.openxmlformats - officedocument.spreadsheetml.sheet'
                //},
                swf: this.swfurl, disableGlobalDnd: true, duplicate: false,//不容許上傳同一個文件
                auto: false,//自動上傳
                server: this.serverurl, fileNumLimit: this.fileNumLimit, formData: this.fmDate, threads: 1, compress: false, //圖片在上傳前不進行壓縮
                fileSizeLimit: 200 * 1024 * 1024,    // 200 M
                fileSingleSizeLimit: 20 * 1024 * 1024,    // 50 M
                chunked: true, //分片處理大文件
                chunkSize: 2 * 1024 * 1024, /* pick: { id: '#filePicker', label: '點擊選擇圖片' }, formData: { uid: 123 }, dnd: '#dndArea', paste: '#uploader', swf: 'Scripts/Uploader.swf', chunked: true, //分片處理大文件 chunkSize: 2 * 1024 * 1024, server: 'fileupload.ashx', disableGlobalDnd: true, threads: 1, //上傳併發數 //因爲Http的無狀態特徵,在往服務器發送數據過程傳遞一個進入當前頁面是生成的GUID做爲標示 formData: { guid: GUID }, fileNumLimit: 300, compress: false, //圖片在上傳前不進行壓縮 fileSizeLimit: 200 * 1024 * 1024, // 200 M fileSingleSizeLimit: 50 * 1024 * 1024 // 50 M */ }); return webUploader; }, /** * 綁定事件 */ bindEvent: function (bindedObj) { var me = this; bindedObj.on('fileQueued', function (file) { var imgHtml = ''; if (file.name.substring(file.name.lastIndexOf("."), file.name.length).indexOf('doc') > -1) { imgHtml = '<img  src="' + me._imgpath +'/doc.ico" />'; } if (file.name.substring(file.name.lastIndexOf("."), file.name.length).indexOf('pdf') > -1) { imgHtml = '<img src="' + me._imgpath +'/apdf.ico" />'; } if (file.name.substring(file.name.lastIndexOf("."), file.name.length).indexOf('els') > -1) { imgHtml = '<img src="' + me._imgpath + '/els.ico" />'; } if (file.name.substring(file.name.lastIndexOf("."), file.name.length).indexOf('png') > -1 || file.name.substring(file.name.lastIndexOf("."), file.name.length).indexOf('jpg') > -1 || file.name.substring(file.name.lastIndexOf("."), file.name.length).indexOf('jpeg') > -1) { imgHtml = '<img src="' + me._imgpath + '/png.ico" />'; } var $li = $('<li name="info" fid="' + file.id + '"  id="' + Math.floor((Math.random() + Math.floor(Math.random() * 9 + 1)) * Math.pow(10, 9)) + me.fileCount + '" class="item">' + imgHtml +
                    '<a class="info" >' + file.name + '</a>' +
                    '<a class="webuploadDelbtn">刪除</a>' +
                    '      <a class="pss">0.00%</a>'+
                    '<br />' +
                    '</li>' ); $li.on("click", ".webuploadDelbtn", function () { $li.find(".webuploadDelbtn").parent().remove(); bindedObj.removeFile(file, true); }); $(me._uploader).find(me._queueList).append($li); me.fileCount++; }); // 文件上傳過程當中建立進度條實時顯示。
            bindedObj.on('uploadProgress', function (file, percentage) { $(me._uploader).find(me._queueList).find('li').each(function () { if ($(this).attr("fid") == file.id) { // alert((percentage * 100) + '%')
                        var _Progress = percentage * 100 >= 100 ? 100 : percentage * 100; $(this).find(".pss").html(_Progress.toFixed(2) + '%'); } }); //var $li = $(me._uploader).find(me._queueList).find("li");
                //var $percent = $li.find('.progress span');
                //alert($li.html());
                //// 避免重複建立 
                //if (!$percent.length) {
                // $percent = $('<p class="progress"><span></span></p>')
                // .appendTo($li)
                // .find('span');
                //}

                //$percent.css('width', percentage * 100 + '%'); 
 }); // 文件上傳成功,給item添加成功class, 用樣式標記上傳成功。
            bindedObj.on('uploadSuccess', function (file, response) { me._messge = response; $(me._uploader).find(me._queueList).find('a.webuploadDelbtn').remove(); me.fileCount--; }); // 文件上傳失敗,顯示上傳出錯。
            bindedObj.on('uploadError', function (file, reason) { }); // 其餘錯誤
            bindedObj.on('error', function (type) { var message = ""; if (type === 'Q_EXCEED_NUM_LIMIT') { message = '最多容許上傳10份'; } if (type == "Q_TYPE_DENIED") { message = "請上傳doc、pdf格式文件"; } else if (type == "F_EXCEED_SIZE") { message =  "文件大小不能超過20M" ; } if ('function' == typeof me.custerror) { me.custerror(message); } // alert(type);
 }); // 完成上傳完了,成功或者失敗
            bindedObj.on('uploadComplete', function (file) { // alert(me.fileCount);
                if (me.fileCount == 0) { //me._completefun.click();
                    ///上傳完後執行的
                    //alert(me._completefun);
                    if (eval(me._completefun) != undefined) eval(me._completefun).apply(this, []); } }); } }; window.$WebUpload = $WebUpload; }());

大功告成!!!!app

相關文章
相關標籤/搜索