码迷,mamicode.com
首页 > Web开发 > 详细

html5上传图片

时间:2016-06-08 15:21:24      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

<!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>

  

html5上传图片

标签:

原文地址:http://www.cnblogs.com/rellame/p/5569998.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!