WebUploader 设置单个文件上传
1.导入控件样式文件
<link rel="stylesheet" type="text/css" href="__PUBLIC__/statics/webuploader-0.1.5/demo.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/statics/webuploader-0.1.5/webuploader.css">
2.导入控件Js文件
<script type="text/javascript" src="__PUBLIC__/statics/webuploader-0.1.5/webuploader.js"></script>
3.HTML代码片段
<tr> <th width="30%">附件:</th> <td> <div class="page-container"> <div id="uploader" class="wu-example"> <div class="queueList"></div> <div class="statusBar" > <div class="btns"> <div id="filePicker"></div> <div class="uploadBtn">开始上传</div> </div> </div> </div> </div> </td> </tr>
4.javascript 实现控件设置
// 文件上传 jQuery(function () { //定义参数 var $ = jQuery, $wrap = $('#uploader'), $queue = $('<ul class="filelist"></ul>') .appendTo($wrap.find('.queueList')), fileCount = 0, fileSize = 0, ratio = window.devicePixelRatio || 1, // 缩略图大小 thumbnailWidth = 110 * ratio, thumbnailHeight = 110 * ratio, percentages = {}, //是否支持旋转 supportTransition = (function () { var s = document.createElement('p').style, r = 'transition' in s || 'WebkitTransition' in s || 'MozTransition' in s || 'msTransition' in s || 'OTransition' in s; s = null; return r; })(), state = 'pedding', //上传按钮 $upload = $wrap.find('.uploadBtn'), errMsg = '上传失败,请重试'; uploader; //实例化 uploader = WebUploader.create({ pick: { id: '#filePicker', label: '点击选择文件' }, accept: { title: 'myself', extensions: 'gif,jpg,jpeg,bmp,png,pdf,doc,docx,xls,xlsx,rar,zip', mimeTypes: 'image/*,application/pdf,application/msword,application/msexcel,application/rar,application/zip,application/vnd.openxmlformats-officedocument.wordprocessingml.document' }, // swf文件路径 swf: '__PUBLIC__/statics/webuploader-0.1.5/Uploader.swf', server: '{:U("Upload/uploaddata")}', duplicate: true }); function setState(val) { var file, stats; if (val === state) { return; } $upload.removeClass('state-' + state); $upload.addClass('state-' + val); state = val; switch (state) { case 'pedding': //待定 $queue.parent().removeClass('filled'); $queue.hide(); uploader.refresh(); break; case 'ready': $('#filePicker').removeClass('element-invisible'); $queue.parent().addClass('filled'); $queue.show(); uploader.refresh(); break; case 'uploading': $('#filePicker').addClass('element-invisible'); $upload.text('暂停上传'); break; case 'paused': $upload.text('继续上传'); break; case 'confirm': $upload.text('开始上传').addClass('disabled'); stats = uploader.getStats(); if (stats.successNum && !stats.uploadFailNum) { setState('finish'); return; } break; case 'finish': stats = uploader.getStats(); console.log(stats); if (stats.successNum) { // alert('上传成功'); layer.msg('上传成功',{icon:1,time:1000}); } else { // 没有成功的图片,重设 state = 'done'; location.reload(); } break; } if (state != "ready") { $('#filePicker').removeClass('element-invisible'); $upload.text('开始上传').removeClass('disabled'); } } function addFile(file) { var $li = $('<li id="' + file.id + '">' + '<p class="title">' + file.name + '</p>' + '<p class="imgWrap"></p>' + '<p class="progress"><span></span></p>' + '</li>'), $btns = $('<div class="file-panel">' + '<span class="cancel">删除</span>' + '<span class="rotateRight">向右旋转</span>' + '<span class="rotateLeft">向左旋转</span></div>').appendTo($li), $prgress = $li.find('p.progress span'), $wrap = $li.find('p.imgWrap'), $info = $('<p class="error"></p>'), showError = function (code) { switch (code) { case 'exceed_size': text = '文件大小超出'; break; case 'interrupt': text = '上传暂停'; break; default: text = errMsg;; break; } $info.text(text).appendTo($li); }; //1.生成缩略图 if (file.getStatus() === 'invalid') { //不合格 showError(file.statusText); } else { // @todo lazyload $wrap.text('预览中'); uploader.makeThumb(file, function (error, src) { if (error) { $wrap.text('不能预览'); return; } var img = $('<img src="' + src + '">'); $wrap.empty().append(img); }, thumbnailWidth, thumbnailHeight); percentages[file.id] = [file.size, 0]; file.rotation = 0; } //2.文件状态变化 file.on('statuschange', function (cur, prev) { //前一个状态 if (prev === 'progress') { //上传中 $prgress.hide().width(0); } else if (prev === 'queued') { //进入队列,等待上传 $li.off('mouseenter mouseleave'); $btns.remove(); } // 成功 if (cur === 'error' || cur === 'invalid') { //失败不合格 showError(file.statusText); percentages[file.id][1] = 1; } else if (cur === 'interrupt') { //暂停 showError('interrupt'); } else if (cur === 'queued') { //队列中 percentages[file.id][1] = 0; } else if (cur === 'progress') { //上传中 $info.remove(); $prgress.css('display', 'block'); } else if (cur === 'complete') { //上传完成 $li.append('<span class="success"></span>'); } $li.removeClass('state-' + prev).addClass('state-' + cur); }); //3.缩略图标签 旋转删除 $li.on('mouseenter', function () { $btns.stop().animate({ height: 30 }); }); $li.on('mouseleave', function () { $btns.stop().animate({ height: 0 }); }); $btns.on('click', 'span', function () { var index = $(this).index(), deg; switch (index) { case 0: uploader.removeFile(file); return; case 1: file.rotation += 90; break; case 2: file.rotation -= 90; break; } if (supportTransition) { deg = 'rotate(' + file.rotation + 'deg)'; $wrap.css({ '-webkit-transform': deg, '-mos-transform': deg, '-o-transform': deg, 'transform': deg }); } else { $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')'); } }); $li.appendTo($queue); } function removeFile(file) { var $li = $('#' + file.id); delete percentages[file.id]; $li.off().find('.file-panel').off().end().remove(); } uploader.onUploadProgress = function (file, percentage) { var $li = $('#' + file.id), $percent = $li.find('.progress span'); $percent.css('width', percentage * 100 + '%'); percentages[file.id][1] = percentage; }; uploader.onFileQueued = function (file) { fileCount++; fileSize += file.size; addFile(file); setState('ready'); }; uploader.onFileDequeued = function (file) { fileCount--; fileSize -= file.size; if (!fileCount) { setState('pedding'); } removeFile(file); }; uploader.on('all', function (type) { var stats; switch (type) { case 'uploadFinished': setState('confirm'); break; case 'startUpload': setState('uploading'); break; case 'stopUpload': setState('paused'); break; } }); uploader.onError = function (code) { // alert('Eroor: ' + code); layer.msg('Eroor: ' + code,{icon:1,time:1000}); }; uploader.on('uploadSuccess',function(file,response){ $('#uploader').append('<input type="hidden" name="urls[]" value="'+response.file_name+'@'+response.url+'" />'); console.log(response); }) uploader.on('uploadAccept', function (file, response) { var hasError = (response["result"] === "error"); if (hasError) { // 通过return false来告诉组件,此文件上传有错。 errMsg = response['error']["message"]; return false; } else { console.log(file); } }); uploader.on('uploadBeforeSend', function (file, data) { data.opr = 'newupload'; data.type = $("#hidtype").val(); data.pid = $("#hidpid").val(); }); //上传按钮 $upload.on('click', function () { if ($(this).hasClass('disabled')) { return false; } if (state === 'ready') { uploader.upload(); } else if (state === 'paused') { uploader.upload(); } else if (state === 'uploading') { uploader.stop(); } }); $upload.addClass('state-' + state); })
5.在上段JavaScript中是设置的多文件上传,可以通过以下方式实现单文件上传
pick: { id: '#filePicker', multiple:false, label: '点击选择图片' }, fileNumLimit: 1,
你对人生迷茫吗?
那就背起行囊,起步远行吧