多图片压缩上传

<form action="upload.php" method="post" id="formss" enctype="multipart/form-data">
	<p><input id="file" type="file" name="imgs[]" multiple accept="image/gif, image/png, image/jpg, image/jpeg"></p>
	<input type="submit" value="提交" />
</form>

结合之前说过的formdata对象,使用canvas获取原图重新绘制,后转换为base64格式图像,使用formdata传送至后台

imgMInity("formss", "file");//第一参数为formid   第二参数为input[file]类型控件id
			function imgMInity(formid, inputid) {
                                //创建formdata对象;
				var formss = document.getElementById(formid);
				var imgform = new FormData(formss);
				var eleFile = document.getElementById(inputid);
				if(window.FormData) {
					// 压缩图片需要的一些元素和对象
					eleFile.addEventListener('change', function(event) {
						for(var i = 0; i < event.target.files.length; i++) {
							file = event.target.files[i];
							if(file.type.indexOf("image") == 0) {
								console.log('已选择图片' + file.name + ',大小为' + Math.round(1000 * file.size / (1024 * 1024)) / 1000 + 'M。');
								var reader = new FileReader(),img = new Image();
								reader.readAsDataURL(file);
								reader.onload = function(e) {
									img.src = e.target.result;
									var canvas = document.createElement('canvas');
									var context = canvas.getContext('2d');
									// base64地址图片加载完毕后
									img.onload = function() {
										console.log("imgonload");
										// 图片原始尺寸
										var originWidth = this.width;
										var originHeight = this.height;
                                                                                               console.log('图片原尺寸是:' + [originWidth, originHeight].join('x'));
// 设置压缩比例或者固定宽高var maxWidth = this.width * 0.8,maxHeight = this.height * 0.8;// 目标尺寸var targetWidth = originWidth,targetHeight = originHeight;if(originWidth > maxWidth || originHeight > maxHeight) {// 图片尺寸超过400x400的限制if(originWidth / originHeight > maxWidth / maxHeight) {// 更宽,按照宽度限定尺寸targetWidth = maxWidth;targetHeight = Math.round(maxWidth * (originHeight / originWidth));} else {targetHeight = maxHeight;targetWidth = Math.round(maxHeight * (originWidth / originHeight));}//alert('超过限制,图片大小限制为' + [targetWidth, targetHeight].join('x'));}canvas.width = targetWidth;canvas.height = targetHeight;// 清除画布context.clearRect(0, 0, targetWidth, targetHeight);// 图片压缩context.drawImage(img, 0, 0, targetWidth, targetHeight);var base64_img = canvas.toDataURL(file.type || 'image/png');imgform.append("img" + i + "", file);//将绘制好的图片添加到formdata中};}} else {alert("您的浏览器不支持压缩上传功能,请使用极速模式或非IE浏览器。");//若浏览器不支持FormData,则无法使用该方法发送图片}}});}}                                                                                                                                            君凯商联网  Alex.Ma
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页