JS原生实现本地图片上传预览

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiao_yu_liu/article/details/64905205
执行方式如下:
$("input").change(function() {
			var config = {
				imgWrapWidth: 300, //px
				imgWrapHeight: 200, //px
				imgMaxWidth: "100%",
				imgMaxHeight: "100%",
			};
			ImgShow(this, "result", config);
		});

函数:
function ImgShow(arg, showWrapId, config) {
			//input的状态change的时候,执行此函数,需要把input用this的方式传递进来,三个参数必须有
			//arg=this   showWrapId=图片显示框的ID     config=显示框的大小和图片显示的大小
			//图片在显示框中绝对居中
			//config = {
//				imgWrapWidth: 300, //px
//				imgWrapHeight: 200, //px
//				imgMaxWidth: "100%",
//				imgMaxHeight: "100%",
//			};
			var file = arg.files[0];
			if(!/image\/\w+/.test(file.type)) {
				alert("请上传图片!");
			} else {
				var reader = new FileReader();
				//将文件以Data URL形式读入页面  
				reader.readAsDataURL(file);
				reader.onload = function(e) {
					var showWrap = document.getElementById(showWrapId);
					showWrap.style.width = config.imgWrapWidth + "px";
					showWrap.style.height = config.imgWrapHeight + "px";
					showWrap.style.textAlign = "center";
					//显示文件  
					showWrap.innerHTML = "<span style='vertical-align: middle;display: inline-block;height: 100%;'></span>" +
						"<img style='vertical-align: middle;display: inline-block;max-width:" + config.imgMaxWidth + ";max-height:" + config.imgMaxHeight + ";'" +
						" src='" + this.result + "' alt='' />";
				}
			}

 

猜你喜欢

转载自blog.csdn.net/xiao_yu_liu/article/details/64905205