博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

webuploader分片上传

Posted on 2018-12-11 11:08  筑筑  阅读(358)  评论(1编辑  收藏  举报

屁话不多说直接上主题;

  1. webuploader,sj(WebUploader 0.1.6)网上有下
  2. powerUpload.js 自己写的基与楼上的插件
  3. asp.net mvc/Api

   实现效果:

        HTML:

<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.插件

 (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;
}());

大功告成!!!!