html5上传图片

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>文件上传</title>
	<style>
	.upload-wrapper {
		font-size: 0;
	}
	.file-input {
		position: relative;
		display: inline-block;
		width: 200px;
		height: 50px;
		line-height: 50px;
		border-radius: 5px;
		text-align: center;
		font-size: 18px;
		font-weight: bold;
		background-color: #009688;
		color: #fff;
		vertical-align: top;
		z-index: 1;
	}
	#upload{
		position: absolute;
		left: 0;
		top: 0;
		width: 200px;
		height: 50px;
		opacity: 0;
	}
	#upload-img {
		display: inline-block;
		margin-left: 30px;
		height: 200px;
	}
	.upload-pic {
		height: 100%;
		width: auto;
	}
	</style>
</head>
<body>
	<div class="upload-wrapper">
		<span class="file-input">上  传<input type="file" id="upload" /></span>
		<div id="upload-img"></div>
	</div>
	<script>
	var input = document.getElementById('upload');
	if(typeof FileReader === undefined) {
		input.setAttribute('disabled','disabled');
	}else {
		input.addEventListener('change',readFile,false);
	}
	function readFile(){
		var file = this.files[0];
		if(!/image\/\w+/.test(file.type)) {
			alert("请选择图片!");
			return false;
		}
		var reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = function(e) {
			var data = this.result.split(',');
			var tp = (file.type == 'image/png') ? 'png' : 'jpg';
			var targetDiv = document.getElementById('upload-img');
			var uploadPic = document.getElementsByClassName('upload-pic');
			if(uploadPic.length === 0) {
				var img = document.createElement('img');
				img.src = data[0]+','+data[1];
				img.className = 'upload-pic';
				targetDiv.appendChild(img);
			}
			else {
				uploadPic[0].src = data[0]+','+data[1];
			}
		//之后的处理将图片数据上传到服务器
		}
	}
	</script>
</body>
</html>

  

posted @ 2016-06-08 14:34  Rella  阅读(169)  评论(0编辑  收藏  举报