webuploader 实现图片批量上传功能附实例代码
程序员文章站
2024-02-26 10:48:40
1、导入资源
2、jsp代码
1、导入资源
2、jsp代码
<div class="page-container"> <div class="row cl"> <label class="form-label col-xs-4 col-sm-2"><span class="c-red">*</span>项目名称:</label> <div class="formcontrols col-xs-8 col-sm-9"> <input type="text" class="input-text" value="${proname }" placeholder="" id="" name="proname" readonly="readonly"> </div> </div> <div class="row cl"> <label class="form-label col-xs-4 col-sm-2">缩略图:</label> <div class="formcontrols col-xs-8 col-sm-9"> <div class="uploader-thum-container"> <div id="filelist" class="uploader-list"></div> <div id="filepicker">选择图片</div> <button id="btn-star" class="btn btn-default btn-uploadstar radius ml-10">开始上传</button> </div> </div> </div> <div class="row cl"> <label class="form-label col-xs-4 col-sm-2"><span class="c-red">*</span>项目发票上传:</label> <div class="formcontrols col-xs-8 col-sm-9"> <div class="uploader-list-container"> <div class="queuelist"> <div id="dndarea" class="placeholder"> <div id="filepicker-2"></div> <p>或将照片拖到这里,单次最多可选300张</p> </div> </div> <div class="statusbar" style="display:none;"> <div class="progress"> <span class="text">0%</span> <span class="percentage"></span> </div> <div class="info"></div> <div class="btns"> <div id="filepicker2"></div> <div class="uploadbtn">开始上传</div> </div> </div> </div> </div> </div> <div class="row cl"> <div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-2"> <button onclick="article_add('','invoicevo/save?&projectid=${projectid}&invoicescan=','10001');" class="btn btn-primary radius" type="button"> <i class="hui-iconfont"></i> 保存 </button> </div> </div> </div>
3、js代码
<script type="text/javascript"> var imagepath=null; function article_save() { alert("刷新父级的时候会自动关闭弹层。"); window.parent.location.reload(); } /*项目发票-添加*/ function article_add(title, url, w, h) { if(imagepath){ var index = layer.open({ type : 2, title : title, content : url+imagepath }); layer.full(index); }else{alert("没有上传图片,请先上传图片");} } $(function() { $('.skin-minimal input').icheck({ checkboxclass : 'icheckbox-blue', radioclass : 'iradio-blue', increasearea : '20%' }); $list = $("#filelist"), $btn = $("#btn-star"), state = "pending", uploader; var uploader = webuploader.create({ auto : true, swf : 'lib/webuploader/0.1.5/uploader.swf',// swf文件路径 // 文件接收服务端。 server : 'lib/webuploader/0.1.5/server/fileupload.php', // 文件接收服务端。 // 选择文件的按钮。可选。 // 内部根据当前运行是创建,可能是input元素,也可能是flash. pick : '#filepicker', // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传! resize : false, // 只允许选择图片文件。 accept : { title : 'images', extensions : 'gif,jpg,jpeg,bmp,png', mimetypes : 'image/*' } }); // 当有文件被添加进队列的时候 uploader .on( 'filequeued', function(file) { var $li = $('<div id="' + file.id + '" class="item">' + '<div class="pic-box"><img></div>' + '<div class="info">' + file.name + '</div>' + '<p class="state">等待上传...</p>' + '</div>'), $img = $li.find('img'); $list.append($li); // 创建缩略图 // 如果为非图片文件,可以不用调用此方法。 // thumbnailwidth x thumbnailheight 为 100 x 100 uploader.makethumb(file, function(error, src) { if (error) { $img.replacewith('<span>不能预览</span>'); return; } $img.attr('src', src); }, thumbnailwidth, thumbnailheight); }); // 文件上传过程中创建进度条实时显示。 uploader .on( 'uploadprogress', function(file, percentage) { var $li = $('#' + file.id), $percent = $li .find('.progress-box .sr-only'); // 避免重复创建 if (!$percent.length) { $percent = $( '<div class="progress-box"><span class="progress-bar radius"><span class="sr-only" style="width:0%"></span></span></div>') .appendto($li).find('.sr-only'); } $li.find(".state").text("上传中"); $percent.css('width', percentage * 100 + '%'); }); // 文件上传成功,给item添加成功class, 用样式标记上传成功。 uploader.on('uploadsuccess', function(file) { $('#' + file.id).addclass('upload-state-success') .find(".state").text("已上传"); }); // 文件上传失败,显示上传出错。 uploader.on('uploaderror', function(file) { $('#' + file.id).addclass('upload-state-error').find(".state") .text("上传出错"); }); // 完成上传完了,成功或者失败,先删除进度条。 uploader.on('uploadcomplete', function(file) { $('#' + file.id).find('.progress-box').fadeout(); }); uploader.on('all', function(type) { if (type === 'startupload') { state = 'uploading'; } else if (type === 'stopupload') { state = 'paused'; } else if (type === 'uploadfinished') { state = 'done'; } if (state === 'uploading') { $btn.text('暂停上传'); } else { $btn.text('开始上传'); } }); $btn.on('click', function() { if (state === 'uploading') { uploader.stop(); } else { uploader.upload(); } }); }); (function($) { // 当domready的时候开始初始化 $(function() { var $wrap = $('.uploader-list-container'), // 图片容器 $queue = $('<ul class="filelist"></ul>').appendto( $wrap.find('.queuelist')), // 状态栏,包括进度和控制按钮 $statusbar = $wrap.find('.statusbar'), // 文件总体选择信息。 $info = $statusbar.find('.info'), // 上传按钮 $upload = $wrap.find('.uploadbtn'), // 没选择文件之前的内容。 $placeholder = $wrap.find('.placeholder'), $progress = $statusbar.find('.progress').hide(), // 添加的文件数量 filecount = 0, // 添加的文件总大小 filesize = 0, // 优化retina, 在retina下这个值是2 ratio = window.devicepixelratio || 1, // 缩略图大小 thumbnailwidth = 110 * ratio, thumbnailheight = 110 * ratio, // 可能有pedding, ready, uploading, confirm, done. state = 'pedding', // 所有文件的进度信息,key为file id percentages = {}, // 判断浏览器是否支持图片的base64 issupportbase64 = (function() { var data = new image(); var support = true; data.onload = data.onerror = function() { if (this.width != 1 || this.height != 1) { support = false; } } data.src = "data:image/gif;base64,r0lgodlhaqabaiaaaaaaap///ywaaaaaaqabaaacauwaow=="; return support; })(), // 检测是否已经安装flash,检测flash的版本 flashversion = (function() { var version; try { version = navigator.plugins['shockwave flash']; version = version.description; } catch (ex) { try { version = new activexobject( 'shockwaveflash.shockwaveflash') .getvariable('$version'); } catch (ex2) { version = '0.0'; } } version = version.match(/\d+/g); return parsefloat(version[0] + '.' + version[1], 10); })(), 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; })(), // webuploader实例 uploader; if (!webuploader.uploader.support('flash') && webuploader.browser.ie) { // flash 安装了但是版本过低。 if (flashversion) { (function(container) { window['expressinstallcallback'] = function(state) { switch (state) { case 'download.cancelled': alert('您取消了更新!') break; case 'download.failed': alert('安装失败') break; default: alert('安装已成功,请刷新!'); break; } delete window['expressinstallcallback']; }; var swf = 'expressinstall.swf'; // insert flash object var html = '<object type="application/' + 'x-shockwave-flash" data="' + swf + '" '; if (webuploader.browser.ie) { html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '; } html += 'width="100%" height="100%" style="outline:0">' + '<param name="movie" value="' + swf + '" />' + '<param name="wmode" value="transparent" />' + '<param name="allowscriptaccess" value="always" />' + '</object>'; container.html(html); })($wrap); // 压根就没有安转。 } else { $wrap .html('<a href="http://www.adobe.com/go/getflashplayer" target="_blank" border="0"><img alt="get flash player" src="http://www.adobe.com/macromedia/style_guide/images/160x41_get_flash_player.jpg" /></a>'); } return; } else if (!webuploader.uploader.support()) { alert('web uploader 不支持您的浏览器!'); return; } // 实例化 uploader = webuploader.create({ pick : { id : '#filepicker-2', label : '点击选择图片' }, formdata : { uid : 123 }, dnd : '#dndarea', paste : '#uploader', swf : 'lib/webuploader/0.1.5/uploader.swf', chunked : false, chunksize : 512 * 1024, server : 'invoicevo/news_uploder?&projectid=${projectid}', // runtimeorder: 'flash', // accept: { // title: 'images', // extensions: 'gif,jpg,jpeg,bmp,png', // mimetypes: 'image/*' // }, // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候,把图片打开。 disableglobaldnd : true, filenumlimit : 300, filesizelimit : 200 * 1024 * 1024, // 200 m filesinglesizelimit : 50 * 1024 * 1024 // 50 m }); // 拖拽时不接受 js, txt 文件。 uploader.on('dndaccept', function(items) { var denied = false, len = items.length, i = 0, // 修改js类型 unallowed = 'text/plain;application/javascript '; for (; i < len; i++) { // 如果在列表里面 if (~unallowed.indexof(items[i].type)) { denied = true; break; } } return !denied; }); uploader.on('dialogopen', function() { console.log('here'); }); // uploader.on('filesqueued', function() { // uploader.sort(function( a, b ) { // if ( a.name < b.name ) // return -1; // if ( a.name > b.name ) // return 1; // return 0; // }); // }); // 添加“添加文件”的按钮, /* uploader.addbutton({ id : '#filepicker2', label : '继续添加' }); */ uploader.on('ready', function() { window.uploader = uploader; }); // 当有文件添加进来时执行,负责view的创建 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 = '上传失败,请重试'; break; } $info.text(text).appendto($li); }; if (file.getstatus() === 'invalid') { showerror(file.statustext); } else { // @todo lazyload $wrap.text('预览中'); uploader .makethumb( file, function(error, src) { var img; if (error) { $wrap.text('不能预览'); return; } if (issupportbase64) { img = $('<img src="'+src+'">'); $wrap.empty().append(img); } else { $ .ajax( 'lib/webuploader/0.1.5/server/preview.php', { method : 'post', data : src, datatype : 'json' }) .done( function( response) { if (response.result) { img = $('<img src="'+response.result+'">'); $wrap .empty() .append( img); } else { $wrap .text("预览出错"); } }); } }, thumbnailwidth, thumbnailheight); percentages[file.id] = [ file.size, 0 ]; file.rotation = 0; } 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') { console.log(file.statustext); 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); }); $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); } // 负责view的销毁 function removefile(file) { var $li = $('#' + file.id); delete percentages[file.id]; updatetotalprogress(); $li.off().find('.file-panel').off().end().remove(); } function updatetotalprogress() { var loaded = 0, total = 0, spans = $progress.children(), percent; $.each(percentages, function(k, v) { total += v[0]; loaded += v[0] * v[1]; }); percent = total ? loaded / total : 0; spans.eq(0).text(math.round(percent * 100) + '%'); spans.eq(1).css('width', math.round(percent * 100) + '%'); updatestatus(); } function updatestatus() { var text = '', stats; if (state === 'ready') { text = '选中' + filecount + '张图片,共' + webuploader.formatsize(filesize) + '。'; } else if (state === 'confirm') { stats = uploader.getstats(); if (stats.uploadfailnum) { text = '已成功上传' + stats.successnum + '张照片至xx相册,' + stats.uploadfailnum + '张照片上传失败,<a class="retry" href="#" rel="external nofollow" rel="external nofollow" >重新上传</a>失败图片或<a class="ignore" href="#" rel="external nofollow" rel="external nofollow" >忽略</a>' } } else { stats = uploader.getstats(); text = '共' + filecount + '张(' + webuploader.formatsize(filesize) + '),已上传' + stats.successnum + '张'; if (stats.uploadfailnum) { text += ',失败' + stats.uploadfailnum + '张'; } } $info.html(text); } function setstate(val) { var file, stats; if (val === state) { return; } $upload.removeclass('state-' + state); $upload.addclass('state-' + val); state = val; switch (state) { case 'pedding': $placeholder.removeclass('element-invisible'); $queue.hide(); $statusbar.addclass('element-invisible'); uploader.refresh(); break; case 'ready': $placeholder.addclass('element-invisible'); $('#filepicker2').removeclass('element-invisible'); $queue.show(); $statusbar.removeclass('element-invisible'); uploader.refresh(); break; case 'uploading': $('#filepicker2').addclass('element-invisible'); $progress.show(); $upload.text('暂停上传'); break; case 'paused': $progress.show(); $upload.text('继续上传'); break; case 'confirm': $progress.hide(); $('#filepicker2').removeclass('element-invisible'); $upload.text('开始上传'); stats = uploader.getstats(); if (stats.successnum && !stats.uploadfailnum) { setstate('finish'); return; } break; case 'finish': stats = uploader.getstats(); if (stats.successnum) { alert('上传成功'); } else { // 没有成功的图片,重设 state = 'done'; location.reload(); } break; } updatestatus(); } uploader.onuploadprogress = function(file, percentage) { var $li = $('#' + file.id), $percent = $li .find('.progress span'); $percent.css('width', percentage * 100 + '%'); percentages[file.id][1] = percentage; updatetotalprogress(); }; uploader.onfilequeued = function(file) { filecount++; filesize += file.size; if (filecount === 1) { $placeholder.addclass('element-invisible'); $statusbar.show(); } addfile(file); setstate('ready'); updatetotalprogress(); }; uploader.onfiledequeued = function(file) { filecount--; filesize -= file.size; if (!filecount) { setstate('pedding'); } removefile(file); updatetotalprogress(); }; /*获取服务器返回的数据*/ uploader.on('uploadsuccess', function(file, response) { alert(response.status); if (response.status == "success") { imagepath =response.filepath; alert("文件保存路径:" + response.filepath); } else if (response.status == "error") alert(response.error); }); uploader.on('all', function(type) { var stats; //alert(type); switch (type) { case 'uploadfinished': setstate('confirm'); break; case 'startupload': setstate('uploading'); break; case 'stopupload': setstate('paused'); break; } }); uploader.onerror = function(code) { alert('eroor: ' + code); }; $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(); } }); $info.on('click', '.retry', function() { uploader.retry(); }); $info.on('click', '.ignore', function() { alert('todo'); }); $upload.addclass('state-' + state); updatetotalprogress(); }); })(jquery); </script>
注意:
4、controller代码
/** * 跳转到上传发票的页面 * @param proname * @param map * @return */ @requestmapping(value = "/upload" ) public string invoiceupload(string proname,long id,map<string, object> map){ map.put("proname", proname); projectservice.getproject(id); map.put("projectid", id); return "project/invoiceupload"; } /** * 上传发票并保存导数据库 * @param file * @param request * @param response * @return */ @responsebody @requestmapping(value = "/news_uploder", method ={requestmethod.post,requestmethod.get}, produces = "application/json; charset=utf-8") public jsonobject uploder(@requestparam multipartfile[] file,long projectid,httpservletrequest request,httpservletresponse response){ string flag=null; jsonobject jsonobject = new jsonobject(); try { webuploaderutil webuploaderutil=new webuploaderutil(); webuploaderutil.upload(file[0], "upload/invoice/", request); flag=webuploaderutil.getfilename(); jsonobject.put("filepath", flag); jsonobject.put("status", "success"); } catch (exception e) { e.printstacktrace(); } return jsonobject; } 5、工具类 package com.softjx.util; /** *project name: qdlimap *file name: webuploaderutil.java *package name: com.ltmap.platform.cms.util *date: 2017年4月13日 下午6:30:45 *copyright (c) 2017,578888218@qq.com all rights reserved. */ import java.io.file; import java.text.simpledateformat; import java.util.date; import javax.servlet.http.httpservletrequest; import org.springframework.web.multipart.multipartfile; /** *title: webuploaderutil<br/> *description: *@company: 励图高科<br/> *@author: 刘云生 *@version: v1.0 *@since: jdk 1.8.0_40 *@date: 2017年4月13日 下午6:30:45 <br/> */ public class webuploaderutil { private string allowsuffix = "jpg,png,gif,jpeg";//允许文件格式 private long allowsize = 2l;//允许文件大小 private string filename; private string[] filenames; public string getallowsuffix() { return allowsuffix; } public void setallowsuffix(string allowsuffix) { this.allowsuffix = allowsuffix; } public long getallowsize() { return allowsize*1024*1024; } public void setallowsize(long allowsize) { this.allowsize = allowsize; } public string getfilename() { return filename; } public void setfilename(string filename) { this.filename = filename; } public string[] getfilenames() { return filenames; } public void setfilenames(string[] filenames) { this.filenames = filenames; } /** * * @title: getfilenamenew * @description: todo * @param: @return * @return: string * @author: 刘云生 * @date: 2017年4月14日 上午10:17:35 * @throws */ private string getfilenamenew(){ simpledateformat fmt = new simpledateformat("yyyymmddhhmmsssss"); return fmt.format(new date()); } /** * * @title: uploads * @description: todo * @param: @param files * @param: @param destdir * @param: @param request * @param: @throws exception * @return: void * @author: 刘云生 * @date: 2017年4月14日 上午10:17:14 * @throws */ public void uploads(multipartfile[] files, string destdir,httpservletrequest request) throws exception { string path = request.getcontextpath(); string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path; try { filenames = new string[files.length]; int index = 0; for (multipartfile file : files) { string suffix = file.getoriginalfilename().substring(file.getoriginalfilename().lastindexof(".")+1); int length = getallowsuffix().indexof(suffix); if(length == -1){ throw new exception("请上传允许格式的文件"); } if(file.getsize() > getallowsize()){ throw new exception("您上传的文件大小已经超出范围"); } string realpath = request.getsession().getservletcontext().getrealpath("/"); file destfile = new file(realpath+destdir); if(!destfile.exists()){ destfile.mkdirs(); } string filenamenew = getfilenamenew()+"."+suffix;// file f = new file(destfile.getabsolutefile()+"\\"+filenamenew); file.transferto(f); f.createnewfile(); filenames[index++] =basepath+destdir+filenamenew; } } catch (exception e) { throw e; } } /** * * @title: upload * @description: todo * @param: @param file * @param: @param destdir * @param: @param request * @param: @throws exception * @return: void * @author: 刘云生 * @date: 2017年4月14日 上午10:16:16 * @throws */ public void upload(multipartfile file, string destdir,httpservletrequest request) throws exception { string path = request.getcontextpath(); //http://localhost:8088/huahang string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path; try { string suffix = file.getoriginalfilename().substring(file.getoriginalfilename().lastindexof(".")+1); int length = getallowsuffix().indexof(suffix); if(length == -1){ throw new exception("请上传允许格式的文件"); } if(file.getsize() > getallowsize()){ throw new exception("您上传的文件大小已经超出范围"); } string realpath = request.getsession().getservletcontext().getrealpath("/")+"/"; file destfile = new file(realpath+destdir); if(!destfile.exists()){ destfile.mkdirs(); } string filenamenew = getfilenamenew()+"."+suffix; file f = new file(destfile.getabsolutefile()+"/"+filenamenew); file.transferto(f); f.createnewfile(); //包含网站的全路径http://localhost:8080/qdlimap/upload/user/20170414104142667.png //filename = basepath+destdir+filenamenew; //返回相对路径upload/user/20170414104142667.png filename = destdir+filenamenew; } catch (exception e) { throw e; } } }
总结
以上所述是小编给大家介绍的webuploader 实现图片批量上传功能附实例代码,希望对大家有所帮助