前端js实现图片上传预览

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Miss_Liang/article/details/72866609

前端js实现图片上传

前端js实现图片上传的原理是通过input标签的type=file属性将input标签定义为上传文件,对input进行onchange事件的监听,当input的value值改变时代表用户已经上传了图片,而input的value值就是用户上传的图片的相对路径,new一个FileReader对象,将图片转换成base64格式的编码,动态创建img标签并将转换后的编码赋值给img标签的src属性即可。

首先,进行页面布局,页面布局是用的浮动布局。

<div class="content clearFlex">
			<form action="" enctype="multipart/form-data">
				<div class="upImg clearFlex">
					<div class="imgOnloadWrap"></div>
					<div class="upWrap">
						<div class="fileWrap">
							<input type="file" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" onchange="upImg(this)"/>
						</div>
						<div class="imgWrap">
							<img src="img/icon6.png" alt="" />
						</div>
					</div>
				</div>
			</form>
		</div>

其次对页面布局进行样式设计

.content{
	width:1000px;
	height: 800px;
	background:#fff;
	border-radius:10px;
	padding:10px;
	overflow-y: scroll;
	margin:0 auto;
	border:1px solid #333;
	border-color:rgba(169,169,169,1);
}
.upWrap{
	width:140px;
	height: 80px;
	margin:10px;
	float: left;
	position: relative;
}
.upWrap > .fileWrap,.upWrap > .fileWrap > input[type=file],.upWrap > .imgWrap{
	position: absolute;
	height: 100%;
	width:100%;
	top:0;
	left:0;
}
.upWrap > .fileWrap > input[type=file]{
	z-index: 2;
	opacity: 0;
}
.upWrap > .imgWrap{
	z-index: 1;
}
.upWrap > .imgWrap > img{
	width:100%;
	height: 100%;
}
.upedImg{
	z-index: 3 !important;
}
.upedImg > span.deleteImg{
	position:absolute;
	content: 'X';
	width:20px;
	font-size: 16px;
	color:#ff0000;
	background:rgba(0,0,0,0.6);
	height:20px;
	text-align: center;
	line-height: 20px;
	right:0;
	top:0;
	z-index:4;
}
.clearFlex:after{
	clear: both;
	content: '';
	display: block;
	height: 0;
	zoom:1;
}

最后对上传图片进行逻辑交互

/*------------------------------上传图片---------------------------*/
function upImg(obj){
	var imgFile = obj.files[0];
	console.log(imgFile);
	var img = new Image();
	var fr = new FileReader();
	fr.onload = function(){
		var htmlStr = '<div class="upWrap">';
		htmlStr += '<div class="fileWrap">';
		htmlStr += '<input type="file" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" onchange="upImg(this)"/>';
		htmlStr += '</div>';
		htmlStr += '<div class="imgWrap upedImg"><span class="deleteImg">X</span>';
		htmlStr += '<img src="'+fr.result+'" alt="" />';
		htmlStr += '</div>';
		htmlStr += '</div>';
		$('.imgOnloadWrap').append(htmlStr);
		obj.value = '';
	}
	fr.readAsDataURL(imgFile);
}
/*-----------------------------删除图片------------------------------*/
$(document).on('click','.upedImg .deleteImg',function(){
	//处理未来事件
	$(this).parent().parent().remove();
})


猜你喜欢

转载自blog.csdn.net/Miss_Liang/article/details/72866609