百度文件上传组件webUploader的使用demo--上传图片(支持多图片上传)
1.依赖的jar

2.页面导入依赖的js和css--jquery.js,webuploader.js,webuploader.css
<script charset="utf-8" src="${ctx}/script/webuploader.js"></script>
<link rel="stylesheet" type="text/css" href="${ctx}/style/webuploader.css" />
3.index.jsp页面布局--可根据具体需求调整
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ include file="/resource/taglibs.jsp" %>
<%@ include file="/resource/script.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script charset="utf-8" src="${ctx}/script/webuploader.js"></script>
<script charset="utf-8" src="${ctx}/script/cxuploader.js"></script>
<link rel="stylesheet" type="text/css" href="${ctx}/style/webuploader.css" />
<link rel="stylesheet" type="text/css" href="${ctx}/style/cxuploader.css" />
<script type="text/javascript">
</script>
<style type="text/css">
body{
padding:0px;
margin: 0px;
}
.head {
height: 80px;
width:100%;
line-height: 80px;
text-align: center;
font-size: 28px;
background-color: rgba(224, 224, 224, 0.72);
}
.content{
margin: 20px;
}
.content ul {
list-style: none;
}
.content ul li{
list-style: none;
width:50%;
float:left;
}
</style>
</head>
<body>
<h1>hello word</h1>
<form id="nhReportForm" name="nhReportForm" action="${contextPath}burket/burketList" method="POST">
<input type="button" value="提交" onclick="this.form.submit()"/>
</form>
<div class="head">单图上传</div>
<div class="content">
<ul>
<li>
<div class="uploder-container">
<div class="cxuploder">
<div class="queueList">
<div class="placeholder">
<div class="filePicker"></div>
<p>将照片拖到这里</p>
</div>
</div>
<div class="statusBar" style="display:none;">
<div class="btns">
<div class="jxfilePicker"></div>
</div>
<div class="info"></div>
</div>
</div>
</div>
</li>
</ul>
</div>
</body>
</html>
4.自定义js--包括webUploader操作的js
cxuploader.js
jQuery(function() { uploader = new Array();//创建 uploader数组 // 优化retina, 在retina下这个值是2 var ratio = window.devicePixelRatio || 1, // 缩略图大小 thumbnailWidth = 100 * ratio, thumbnailHeight = 100 * ratio, 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; })(); // 所有文件的进度信息,key为file id var percentages = {}; var state = 'pedding'; //可行性判断 if ( !WebUploader.Uploader.support() ) { alert( 'Web Uploader 不支持您的浏览器!如果你使用的是IE浏览器,请尝试升级 flash 播放器'); throw new Error( 'WebUploader does not support the browser you are using.' ); } //循环页面中每个上传域 $('.uploder-container').each(function(index){ // 添加的文件数量 var fileCount = 0; // 添加的文件总大小 var fileSize = 0; var filePicker=$(this).find('.filePicker');//上传按钮实例 var queueList=$(this).find('.queueList');//拖拽容器实例 var jxfilePicker=$(this).find('.jxfilePicker');//继续添加按钮实例 var placeholder=$(this).find('.placeholder');//按钮与虚线框实例 var statusBar=$(this).find('.statusBar');//再次添加按钮容器实例 var info =statusBar.find('.info');//提示信息容器实例 // 图片容器 var queue = $('<ul class="filelist"></ul>').appendTo( queueList); //初始化上传实例 uploader[index] = WebUploader.create({ // 选完文件后,是否自动上传。 auto : true, // swf文件路径 swf: '${ctx}/swf/Uploader.swf', //处理上传按钮 pick: { id: filePicker, multiple : true,//是否可以多选 label: '上传' }, dnd: queueList, //这里可以根据 index 或者其他,使用变量形式 accept: { title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png,doc', mimeTypes: 'image/*' }, //禁用浏览器的拖拽功能,否则图片会被浏览器打开 disableGlobalDnd: true, //是否分片处理大文件的上传 chunked: false, //上传地址 server: 'burket/pictureUploder', //一次最多上传文件个数 fileNumLimit: 5, // 总共的最大限制10M fileSizeLimit: 10 * 1024 * 1024, // 单文件的最大限制3M fileSingleSizeLimit: 3 * 1024 * 1024 , //duplicate属性,重复上传,是可选的, true为可重复 ,false为不可重复 默认为undifind 也是不可重复。 duplicate : true, formData: { token:index//可以在这里附加控件编号,从而区分是哪个控件上传的 } }); // 添加“继续添加文件”的按钮 uploader[index].addButton({ id: jxfilePicker, label: '继续添加' }); //当文件加入队列时触发 uploader[index].onFileQueued = function( file ) { fileCount++; fileSize += file.size; if ( fileCount === 1 ) { placeholder.addClass( 'element-invisible' ); statusBar.show(); } addFile( file,uploader[index],queue); setState( 'ready' ,uploader[index],placeholder,queue,statusBar,jxfilePicker); updateStatus('ready',info,fileCount,fileSize); }; //当文件被移除队列后触发。 uploader[index].onFileDequeued = function( file ) { fileCount--; fileSize -= file.size; if ( !fileCount ) { setState( 'pedding',uploader[index],placeholder,queue,statusBar,jxfilePicker); updateStatus('pedding',info,fileCount,fileSize); } removeFile( file ); }; //上传成功触发 uploader[index].on('uploadSuccess',function(file,reponse){ alert("上传成功"); }); //上传操作之前触发,可以在这里附加额外上传数据 uploader[index].on('uploadBeforeSend',function(object,data,header) { /*var tt=$("input[name='id']").val(); data=$.extend(data,{ modelid:tt });*/ //alert("上传前触发"); }); }); // 文件上传失败,显示上传出错。 uploader.on( 'uploadError', function( file ) { var $li = $( '#'+file.id ), $error = $li.find('div.error'); // 避免重复创建 if ( !$error.length ) { $error = $('<div class="error"></div>').appendTo( $li ); } $error.text('上传失败'); }); // 当有文件添加进来时执行,负责view的创建 function addFile( file,now_uploader,queue) { 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>'); $wrap.text( '预览中' ); if(file.flog == true){ var img = $('<img src="'+file.ret+'">'); $wrap.empty().append( img ); }else{ now_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; /* 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: now_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 ]; $li.off().find('.file-panel').off().end().remove(); } function setState( val, now_uploader,placeHolder,queue,statusBar,jxfilePicker) { switch ( val ) { case 'pedding': placeHolder.removeClass( 'element-invisible' ); queue.parent().removeClass('filled'); queue.hide(); statusBar.addClass( 'element-invisible' ); now_uploader.refresh(); break; case 'ready': placeHolder.addClass( 'element-invisible' ); jxfilePicker.removeClass( 'element-invisible'); queue.parent().addClass('filled'); queue.show(); statusBar.removeClass('element-invisible'); now_uploader.refresh(); break; } } function updateStatus(val,info,f_count,f_size) { var text = ''; if ( val === 'ready' ) { text = '选中' + f_count + '张图片,共' + WebUploader.formatSize( f_size ) + '。'; } info.html( text ); } });
5.controller
@RequestMapping(value = "/burket/pictureUploder", method = {RequestMethod.GET,RequestMethod.POST}) public ModelAndView pictureUploder(HttpServletRequest request, HttpServletResponse response ) throws Exception { Map<String, Object> result = new HashMap<String, Object>(); try { //判断是否上传了图片 boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { result.put("success", "false"); result.put("message", "请上传图片"); //renderText(dataToJson(result)); return null; } //文件分析器 MultipartResolver MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext()); MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request); Map<String, MultipartFile> map = multipartRequest.getFileMap(); //判断上传文件的格式 MultipartFile cmf = map.get("file"); if (cmf.getOriginalFilename().contains(".")) { String fileName[] = cmf.getOriginalFilename().split("\\."); String sux=fileName[fileName.length-1]; if (!"jpg".equalsIgnoreCase(sux) && !"png".equalsIgnoreCase(sux) && !"JPEG".equalsIgnoreCase(sux) &&!"bmp".equalsIgnoreCase(sux)) { result.put("success", "false"); result.put("message", "只能上传'jpg,jpeg,bmp,png'格式的图片"); //renderText(dataToJson(result)); return null; } } //判断上传图片的像素及比例 BufferedImage bi = null; bi = ImageIO.read(cmf.getInputStream()); int width = bi.getWidth(); int height = bi.getHeight(); if(width<800||height<600||width/height!=4/3){ result.put("success", "false"); result.put("message", "请上传像素不小于800*600且比例为4:3的图片"); //renderText(dataToJson(result)); return null; } //判断上传文件的大小 Long size = cmf.getSize(); double megaSize = size.doubleValue()/(1024*1024); if(megaSize>1d){ result.put("success", "false"); result.put("message", "请上传不大于1M的图片文件!"); //renderText(dataToJson(result)); return null; } //处理上传文件 List<FileUploadVo> fvs = new ArrayList<FileUploadVo>(); for (String key : map.keySet()) { CommonsMultipartFile cmf1 = (CommonsMultipartFile) map.get(key); if (cmf1.isEmpty()) { continue; } FileUploadVo fuv = new FileUploadVo(); fuv.setInputStream(cmf.getInputStream()); // 获取上传的完整原文件名 String oldFileName = cmf.getOriginalFilename(); // 获取上传的原文件名 文件名中不包括 . 则认为文件非法 //String originalFilename = AppFileUploadUtils.getOriginalFileName(cmf.getOriginalFilename()); String originalFilename =null; // 获取文件源文件后缀名 //String fileExtendName = AppFileUploadUtils.getFileExtension(oldFileName); String fileExtendName = null; if (cmf.getOriginalFilename().contains(".")) { originalFilename = cmf.getOriginalFilename().substring(0, cmf.getOriginalFilename().lastIndexOf(".")); fileExtendName = cmf.getOriginalFilename().substring(cmf.getOriginalFilename().lastIndexOf(".") + 1); } // 生成新文件名 //String newFileName = JugHelper.generalUUID(); String newFileName = UUID.randomUUID().toString().replace("-", "").toLowerCase(); //附件对应的实体类 NhAttachment lvAttachment = new NhAttachment(); lvAttachment.setId(newFileName); lvAttachment.setOriginalFileName(originalFilename); lvAttachment.setStorageFileName(newFileName); lvAttachment.setFileExtendName(fileExtendName); lvAttachment.setUploadFilePath(null); // lvAttachment.setFileSize(null); lvAttachment.setUploadTime(null); lvAttachment.setFileSize(cmf.getSize()); lvAttachment.setStateSign(NhAttachment.STATE_SIGN_USE); fuv.setAttachment(lvAttachment); fvs.add(fuv); } //List<FileUploadVo> vos = getFileUploadVos(); if (fvs == null || fvs.isEmpty()) { return null; } // 返回的结果信息 //Set<NhAttachment> result = new HashSet<NhAttachment>(); // 按日期生成文件夹 Integer sortNum = 1; for (FileUploadVo fuv : fvs) { InputStream ins = fuv.getInputStream(); NhAttachment attachment = fuv.getAttachment(); String fullFileName = attachment.getStorageFileName() + "." + attachment.getFileExtendName(); // 文件上传 Map<String, String> uploadResult = null; try { //uploadResult = AppFileUploadUtils.uploadPicWithWaterMarker(ins, fullFileName,waterMakerPath); String fileSize = "0"; BufferedInputStream in = null; BufferedOutputStream out = null; // 文件上传路径前缀 String basePath = "E:"; String relativePath = "\\upload"; // 完整文件名称 String fullFilePath = ""; // 返回上传附件信息 try { // 获得文件输入流 in = new BufferedInputStream(ins); // 文件的相对路径 File file = new File(basePath + relativePath); // 若文件夹不存在,则递归创建文件夹 if (!file.exists()) { file.mkdirs(); } // 文件全路径 fullFilePath = basePath + relativePath + SEPARATOR + fullFileName; File f = new File(fullFilePath); // 获得文件输出流 out = new BufferedOutputStream(new FileOutputStream(f)); // 写入文件 Streams.copy(in, out, true); fileSize = String.valueOf(f.length()); } finally { try { if (out != null) { out.close(); } } finally { if (in != null) { in.close(); } } } } catch (IOException e) { e.printStackTrace(); //throw new AppSysException("SE101007"); } } //result.put("file", ls); result.put("success", "true"); //renderText(dataToJson(result)); return null; } catch (Exception e) { e.printStackTrace(); result.put("success", "false"); result.put("message", "上传图片格式不正确,请不要改图片后缀名"); //renderText(dataToJson(result)); return null; }
}

浙公网安备 33010602011771号