webuploader在同一个页面支持多个按钮实例,类似京东那样的评论

     之前在公司做电商时候用到webuploader ,起初是支持单实例,后来要求支持多实例,当时工作忙没有写博客,现在闲下来了 所以个人写个总结。

         webuploder API网址,如果不懂我说的可以去查看http://fex.baidu.com/webuploader/doc/index.html#WebUploader_Uploader_addButton


1.首先是页面   

  

 <form id="form_config_{{=ord.odetId}}" class="evalu" method="post">
	<div class="per_evaluate2 flW" >
		<div class="per_evaluate_btm per_evaluate_bor">

			<table width="100%" border="0" cellspacing="0" cellpadding="0" style="display:none"  id="form-horizontal_{{=ord.odetId}}">
				<tbody>
					<tr>
						<td width="8%" align="right">评分:</td>
						<td width="92%">
							<div class="w-orderList" style="display:block">
								<div class="w-orderList-content">
									  <span> <em class="w-specifications" id="w-stars_{{=ord.odetId}}" ></em><br /></span> <input type="hidden" name="starCount"
										id="starCount_{{=ord.odetId}}" value="" /> <input type="hidden" name="prodId" id="prodId" value="{{=ord.prod_id}}" /> <input type="hidden" name="orderDetailId"
										id="orderDetailId" value="{{=ord.odetId}}" />

								</div>
						</td>
					</tr>
					<tr>
						<td align="right" valign="top">评价:</td>
						<td><textarea class="per_evaluate_textarea w_require w_content" name="content" id="Etxt_{{=ord.odetId}}" placeholder="(1-500字)请写下您对商品的感受,您的评价对他人有很大的帮助哦~"></textarea></td>
					</tr>
					<tr>
						<td> </td>
						<td>
              <div class=" w-addPhoto">
				<div class="">
					<label class="">评价图片:<span class="required"> * </span>
					</label>
					<div>
						<div id="uploader">
							<div id="uploader-demo" style="padding-left: 37px;  padding-right: 37px;">
								<input type="hidden" name="picuri" id="picurl_wx_{{=ord.odetId}}" value="1" />
								<div id="imgPathWebUploader_{{=ord.odetId}}" style="display: none"></div>
								<div id="filePicker_{{=ord.odetId}}" οnclick="deal({{=ord.odetId}});" style="">选择图片(最多上传5张图片)</div>
								<!--用来存放item-->
								<div style="margin-left: 40px;margin-top: 10px;display: none;text-align:left" id="isfirstWebUploader_{{=ord.odetId}}"></div>
								<div id="fileList_{{=ord.odetId}}" οnmοuseοver="bigImg({{=ord.odetId}})" class="uploader-list filelist"></div>
							</div>
						</div>
						<!-- 图片建议尺寸为350*350,比例1比1 -->
					</div>
				</div>
			</div>
						</td>
					</tr>
					<tr>
						<td> </td>
						<td><input type="button" name="submit" id="submit_{{=ord.odetId}}" οnclick="evalution({{=ord.odetId}},{{=ord.prod_id}})"class="per_evaluate_btn upload_btn" value="提交评价" ></td>
					</tr>
				</tbody>
			</table>
		</div>
	</div>
	</form>

我们用的模板是doT.js来遍历集合  当然也有很多其他方式 比如说最近见到 用easyui框架 也可以显示列表

2. JavaScript 

 

var oldImgUrl = '${userCommentInfo}';//修改-以前的图片信息json格式
	var evacom = 1;
	var fileNumLimit = 10000;
	var multiple = false;
	var imgtype = "userCommentImg";
	var punit = "${userCommentInfo.unit}";
	if (oldImgUrl != "") {
		getImgByJson(oldImgUrl);
	}

	jQuery(document).ready(function() {
		FormValidation.init();
	});
	function bigImg(id) {
		evacom = id;
	}
	function deal(id) {
		evacom = id;
		$list = $("#fileList_" + evacom);
	}
	function amy_evaluate() {
		$(".per_evaluate").css("display", "block");
	}
	function evaluate_off() {
		$(".per_evaluate").css("display", "none");

	}
//
	function showOrNo(ids) {
		Imgmap = new Map();
		$('#w-stars_' + ids).raty({
			width : 300
		});
		evacom = ids;
		/* var fileNumLimit_evacom = 5; */
		var itid = "#filePicker_" + ids;
		$.each(Imgmothermap, function(i, item) {
			if (ids != item.id) {
				uploader.addButton({
					id : itid,
					innerHTML : '选择图片(最多上传5张图片)',
					multiple : false
				});
			}
		});
		Imgmap = new Map();
		Imgmothermap.put("eva_" + evacom, Imgmap);
		$list = $("#fileList_" + evacom);
		if (Imgmothermap == null) {
			evacom = ids;
			uploader.addButton({
				id : itid,
				innerHTML : '选择图片(最多上传5张图片)',
				multiple : false
			});
		}
		var bloc = "#form-horizontal_" + ids;
		$(bloc).toggle();
	}
3. Upload上传 Java关键代码

@RequestMapping(value = "/getImgurlbyfile", method = RequestMethod.POST)
	public void getImgurlbyfile(HttpServletResponse response,
			HttpServletRequest request) {
		long maxSize = 3000000;// 图片的大小
		JSONObject json = new JSONObject();
		String imgtype = request.getParameter("imgtype");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile myfile = multipartRequest.getFile("imgfile");
		String filePath = null;
		if (Tools.isEmpty(imgtype)) {
			json.put("res_code", "ER1003");
			json.put("res_msg",
					BaseConfig.MESSAGE.get("publicInterface.ER1003"));
		} else {
			if (getBoolByType(myfile.getOriginalFilename().toLowerCase())) {
				if (myfile.getSize() <= maxSize) {
					if (null != myfile && !myfile.isEmpty()) {
						switch (imgtype) {// 判断上传图像类型
						case "productImg":// 商品 300 *300
							filePath = Tools.uploadpicByShow(myfile, imgtype,
									160, 50, 300, 640, 1000);
							json.put("res_code", "0");
							json.put("res_msg", "OK");
							json.put("filePath", filePath);
							break;
						case "userCommentImg":// 商品 200 *200
							filePath = Tools.uploadpicByShow(myfile, imgtype,
									200);
							json.put("res_code", "0");
							json.put("res_msg", "OK");
							json.put("filePath", filePath);
							break;
						default:
							filePath = Tools.uploadpic(myfile, imgtype);
							json.put("res_code", "0");
							json.put("res_msg", "OK");
							json.put("filePath", filePath);
							break;
						}
					} else {
						json.put("res_code", "ER1001");
						json.put("res_msg", BaseConfig.MESSAGE
								.get("publicInterface.ER1001"));
					}
				} else {
					json.put("res_code", "ER1008");
					json.put("res_msg",
							BaseConfig.MESSAGE.get("publicInterface.ER1008"));
				}
			} else {
				json.put("res_code", "ER1007");
				json.put("res_msg",
						BaseConfig.MESSAGE.get("publicInterface.ER1007"));
			}

		}

		try {
			responseAjax(json, response);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

webupload.js

$list = $("#fileList");//图片存放位置
var count=0;//已经上传的照片数量,用于修改删除或者修改的时候,默认成功图片数量
var Imgmap = new Map();//存储图片得map
thumbnailWidth = 100;
thumbnailHeight = 100;
var uploader = WebUploader.create({

	// 选完文件后,是否自动上传。
	auto : true,
	fileVal : 'imgfile',
	formData : {
		imgtype:imgtype
	},
	// swf文件路径
	swf : SHOPDOMAIN+ '/js/webuploader/Uploader.swf',
	duplicate : true,
	// 文件接收服务端。
	server : SHOPDOMAIN+ '/publicinterface/getImgurlbyfile.html',
	// 选择文件的按钮。可选。
	// 内部根据当前运行是创建,可能是input元素,也可能是flash.
	pick : '#filePicker',
	// 只允许选择图片文件。
	accept : {
		title : 'Images',
		extensions : 'gif,jpg,jpeg,bmp,png',
		mimeTypes : 'image/*'
	},
	fileNumLimit :fileNumLimit,
	fileSingleSizeLimit : '3000000'
});
// 当有文件添加进来的时候
uploader.on('fileQueued',function(file) {
	var $li = $('<div id="' + file.id + '" class="file-item thumbnail">'
			+ '<img>'
			+ '<div class="info">'
			+ file.name + '</div>' + '</div>'), $img = $li
			.find('img');
	$btns = $(
			'<div class="file-panel fp_' + file.id + '">'
					+ '<span class="cancel">删除</span></div>')
					
			.appendTo($li);
	$li.on('mouseenter', function() {
		$('.fp_' + file.id).stop()
//		.animate({
//			height : 30
//		});
	});

	$li.on('mouseleave', function() {
		$('.fp_' + file.id).stop()
//		.animate({
//			height : 0
//		});
	});

	$btns.on('click', 'span', function() {
		var index = $(this).index(), deg;
		switch (index) {
		case 0://删除
			uploader.setStats(8);
			delImg(file.id);
			return;

		case 1://右移
			var $nextId=$("#"+file.id).next();
			if(undefined!=$nextId.attr("id")){
				var tempSrc=Imgmap.get($nextId.attr("id"));
				var tempWu_File=$("#"+file.id);
				Imgmap.put($nextId.attr("id"), Imgmap.get(file.id));
				Imgmap.put(file.id, tempSrc);
				$nextId.after(tempWu_File);
				$('.fp_' + file.id).stop().animate({
					height : 0
				});
				$("#imgPathWebUploader").html(Imgmap.toString());
			}
			break;

		case 2://左移
			var $prevId=$("#"+file.id).prev();
			if(undefined!=$prevId.attr("id")){
				var tempSrc=Imgmap.get($prevId.attr("id"));
				var tempWu_File=$("#"+file.id);
				Imgmap.put($prevId.attr("id"), Imgmap.get(file.id));
				Imgmap.put(file.id, tempSrc);
				$prevId.before(tempWu_File);
				$('.fp_' + file.id).stop().animate({
					height : 0
				});
				$("#imgPathWebUploader").html(Imgmap.toString());
			}
			break;
		}
	});

	// $list为容器jQuery实例
	$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 span');

	// 避免重复创建
	if (!$percent.length) {
		$percent = $('<p class="progress"><span></span></p>').appendTo(
				$li).find('span');
	}

	$percent.css('width', percentage * 100 + '%');
});

// 文件上传成功,给item添加成功class, 用样式标记上传成功。
uploader.on('uploadSuccess', function(file, response) {
	Imgmap.put(file.id, response.filePath );
	$("#isfirstWebUploader").css("display","");
	$("#imgPathWebUploader").html(Imgmap.toString());
	$('#' + file.id).addClass('upload-state-done');
});

// 文件上传失败,显示上传出错。
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('上传失败');
});

// 完成上传完了,成功或者失败,先删除进度条。
uploader.on('uploadComplete', function(file) {
	$('#' + file.id).find('.progress').remove();
});

// 完成上传完了,成功或者失败,先删除进度条。
uploader.on('error', function(file) {
	showMessage(file);
});

function delImg(fileId) {
	var tempImgPath = $("#imgPathWebUploader").html();
	Imgmap.remove(fileId);
	if(Imgmap.size()==0){
		$("#isfirstWebUploader").css("display","");
	}
	$("#imgPathWebUploader").html(Imgmap.toString());
	$("#" + fileId).remove();
}

function getImgByJson(json){
	json = eval(json)  
	$("#isfirstWebUploader").css("display","");
	for(var i=0; i<json.length; i++)  
	{  
		Imgmap.put("WU_10000"+json[i].id, json[i].uri);
		var $li = $('<div id="WU_10000' + json[i].id + '" class="file-item thumbnail">'
				+ '<img src="'+USERIMGSRC+imgZuhe(json[i].uri,'_160')+'">'
				+ '<div class="info">'
				+ json[i].uri + '</div>' + '</div>'), $img = $li
				.find('img');
		$btns = $(
				'<div class="file-panel fp_WU_10000' + json[i].id + '" id="'+json[i].id+'">'
						+ '<span class="cancel">删除</span>'
						+ '<span class="rotateRight">向右旋转</span>'
						+ '<span class="rotateLeft">向左旋转</span></div>')
				.appendTo($li);
		$li.on('mouseenter', function() {
			var tempId=$(this).attr("id");
			$('.fp_' + tempId).stop().animate({
				height : 30
			});
		});
	
		$li.on('mouseleave', function() {
			var tempId=$(this).attr("id");
			$('.fp_' + tempId).stop().animate({
				height : 0
			});
		});
	
		$btns.on('click', 'span', function() {
			var tempId=$(this).parent().attr("id");
			var index = $(this).index(), deg;
			switch (index) {
			case 0://删除
				uploader.setStats(8);
				delImg("WU_10000"+tempId);
				return;
	
			case 1://右移
				var $nextId=$("#WU_10000"+tempId).next();
				if(undefined!=$nextId.attr("id")){
					var tempSrc=Imgmap.get($nextId.attr("id"));
					var tempWu_File=$("#WU_10000"+tempId);
					Imgmap.put($nextId.attr("id"), Imgmap.get("WU_10000"+tempId));
					Imgmap.put("WU_10000"+tempId, tempSrc);
					$nextId.after(tempWu_File);
					$('.fp_WU_10000'+tempId).stop().animate({
						height : 0
					});
					$("#imgPathWebUploader").html(Imgmap.toString());
				}
				break;
	
			case 2://左移
				var $prevId=$("#WU_10000"+tempId).prev();
				if(undefined!=$prevId.attr("id")){
					var tempSrc=Imgmap.get($prevId.attr("id"));
					var tempWu_File=$("#WU_10000"+tempId);
					Imgmap.put($prevId.attr("id"), Imgmap.get("WU_10000"+tempId));
					Imgmap.put("WU_10000"+tempId, tempSrc);
					$prevId.before(tempWu_File);
					$('.fp_WU_10000'+tempId).stop().animate({
						height : 0
					});
					$("#imgPathWebUploader").html(Imgmap.toString());
				}
				break;
			}
		});
	
		// $list为容器jQuery实例
		$list.append($li);
	} 
	count=i;
	$("#imgPathWebUploader").html(Imgmap.toString());
}

原理, 就是每次点击按钮的时候 对按钮进行绑定事件

addButton
addButton( pick ) ⇒ Promise
添加文件选择按钮,如果一个按钮不够,需要调用此方法来添加。参数跟options.pick一致。

uploader.addButton({
    id: '#btnContainer',
    innerHTML: '选择文件'
});

每个按钮都有不同的id,所以说webuploader可以实例化多个按钮,这是重点,这样一个页面就支持多个评论了。

这里留下个人的qq 178970412  有问题可以一起讨论 相互学习

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值