[关闭]
@KingMe 2015-12-14T12:20:04.000000Z 字数 4137 阅读 2377

WebUploader Demo

WebUploader JS


WebUploader官网

客户端

使用了 进度条和modal,初始化和销毁事件放在modal的隐藏显示事件中。modal中的click选中区域需要特殊处理

html

                            <div class="row">
                                <div id="uploader" class="wu-example col-md-3">
                                    <!--用来存放文件信息-->
                                    <div id="thelist" class="uploader-list"></div>
                                    <div class="btns">
                                        <div id="picker">上传文件</div>
                                    </div>
                                </div>
                                <div class="col-md-8">
                                    <div class="progress">
                                        <div class="progress-bar" role="progressbar"></div>
                                    </div>
                                </div>
                            </div>

js

var uploader;
var pbar;

var first = true;//用于初始化上传控件
$('.progress').fadeOut();

//弹出窗完全显示,初始化上传控件
$('#modalManual').on('shown.bs.modal', function (e) {

    pbar = $('.progress .progress-bar');
        if (!uploader || !uploader._widgets) {
            initUploadLargeFiles();
        }
    })
    $('#modalManual').on('hidden.bs.modal', function (e) {
    vueFile.$data = getFileInitVue();
    uploader.destroy();
})

function initUploadLargeFiles() {
    uploader = WebUploader.create({
        auto: true,
        swf: '../js/ganning/Plugins/webuploader/Uploader.swf',
        // 文件接收服务端。
        server: '../Ajax/FileHandler.ashx?Oper=AddEmailFile',
        // 内部根据当前运行是创建,可能是input元素,也可能是flash.
        pick: '#picker',
        chunked: true,//开启分片上传
        threads: 1,//上传并发数
        disableGlobalDnd: true,//禁用拖拽
        accept: {
            title: '文档',
            extensions: 'gif,jpg,jpeg,bmp,png,pdf,doc,docx',
            mimeTypes: '*/*'
        },
        //由于Http的无状态特征,在往服务器发送数据过程传递一个进入当前页面是生成的GUID作为标示
        formData: { guid: WebUploader.Base.guid(), Folder: "email" }

    });
    uploader.on('beforeFileQueued', function (file) {
        if (file.size / 1024 / 1024 > 100) {
            layer.alert("error", {
                btn: [$lang["OK"]],
                    title: [$lang["TitleError"]]
            });
            return false;
        } else {
            return true;
        }
    });
    uploader.on('fileQueued', function (file) {
        $('.progress').show();
        });
        // 文件上传过程中创建进度条实时显示。
        uploader.on('uploadProgress', function (file, percentage) {
            pbar.attr('data-transitiongoal', percentage * 100 - 1).progressbar({ display_text: 'center' });
        });
        //上传成功回调
        uploader.on('uploadSuccess', function (file, response) {
            if (response.HasError == 0) {
                vueFile.fileList.push({ MongoDBFileName: file.name, FileSize: file.size, FileType: file.ext, CreateTime: moment().format($lang["Date"]["LongDate"]), ObjectId: response.ObjectId });
            } else {
                AlertError(response.ErrorInfo);
            }
        });
        //上传错误回调
        uploader.on('uploadError', function (file) {
            AlertError("error");
        });
        //上传成功或失败,都会调用
        uploader.on('uploadComplete', function (file) {
            $('.progress').fadeOut();
            pbar.attr('data-transitiongoal', 0).progressbar({ display_text: 'center' });
        });
        //修复model内部点击不会触发选择文件的BUG
        $("#picker .webuploader-pick").click(function () {
        $("#picker :file").click();
    });
}

服务端 .NET

服务端需要考虑分片的情况,根据客户端的GUID来保证不会冲突

 try
        {
            string folder = context.Request.Params["Folder"];
            if (string.IsNullOrEmpty(folder))
            {
                folder = "Temp";
            }
            //如果进行了分片
            if (context.Request.Form.AllKeys.Any(m => m == "chunk"))
            {
                //取得chunk和chunks
                int chunk = Convert.ToInt32(context.Request.Form["chunk"]);
                int chunks = Convert.ToInt32(context.Request.Form["chunks"]);

                //根据GUID创建用该GUID命名的临时文件
                if (!Directory.Exists(context.Server.MapPath("~/temp")))
                {
                    Directory.CreateDirectory(context.Server.MapPath("~/temp"));
                }
                string path = context.Server.MapPath("~/temp/" + context.Request["guid"]);
                FileStream addFile = new FileStream(path, FileMode.Append, FileAccess.Write);
                BinaryWriter AddWriter = new BinaryWriter(addFile);
                //获得上传的分片数据流
                HttpPostedFile file = context.Request.Files[0];
                Stream stream = file.InputStream;

                BinaryReader TempReader = new BinaryReader(stream);
                //将上传的分片追加到临时文件末尾
                AddWriter.Write(TempReader.ReadBytes((int)stream.Length));
                //关闭BinaryReader文件阅读器
                TempReader.Close();
                stream.Close();
                AddWriter.Close();
                addFile.Close();

                TempReader.Dispose();
                stream.Dispose();
                AddWriter.Dispose();
                addFile.Dispose();
                //如果是最后一个分片,则重命名临时文件为上传的文件名
                if (chunk == (chunks - 1))
                {
                    FileInfo fileinfo = new FileInfo(path);
                    Stream chunkstream = fileinfo.OpenRead();
                    string fileData = Convert.ToBase64String(FileHelper.StreamToBytes(chunkstream));
                    chunkstream.Close();
                    fileinfo.Delete();


                    string json = CoreService.FileService.UploadFileSimple(context.Request.Files[0].FileName, fileData, folder, sessionkey, language);
                    return json;
                }
                return JsonConvert.SerializeObject(new { HasError = 0, AllDone = false, ErrorInfo = "" });
            }
            else//没有分片直接保存
            {
                HttpPostedFile file = context.Request.Files[0];
                Stream stream = file.InputStream;
                string fileData = Convert.ToBase64String(FileHelper.StreamToBytes(stream));
                string json = CoreService.FileService.UploadFileSimple(context.Request.Files[0].FileName, fileData, folder, sessionkey, language);
                return json;
            }
        }
        catch (Exception ex)
        {
            return JsonConvert.SerializeObject(new { HasError = 1, AllDone = true, ObjectId = "", ErrorInfo = ex.Message });
        }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注