<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title>简单的上传图片并预览</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
<style>
*{
padding: 0;
margin: 0 auto;
}
.yg_content{
margin-top: 50px;
text-align: center;
}
#upimg{
display: none;
}
.yg_content p{
padding: 10px;
display: inline-block;
color: #fff;
background: #08c;
border: 1px #ccc solid;
border-radius: 10px;
}
.yg_content p:active{
opacity: .5;
}
.showimg{
margin: 20px auto;
border: 1px #ccc solid;
border-radius: 10px;
width: 200px;
height: 200px;
}
.showimg img{
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="yg_content">
<input type="file" id="upimg" accept="image/*" onchange="upLoad()">
<label for="upimg">
<p>点击上传图片</p>
</label>
<div class="showimg">
<img id="img" src="data:images/tx_1.jpg" alt="">
</div>
</div>
</body>
<script>
function upLoad(){
var fileInput = document.getElementById("upimg");
var file = fileInput.files[0];
//创建读取文件的对象
var reader = new FileReader();
//创建文件读取相关的变量
var imgFile;
//为文件读取成功设置事件
reader.onload=function(e) {
// alert('文件读取完成');
imgFile = e.target.result;
console.log(imgFile);
$("#img").attr('src',imgFile);
};
//正式读取文件
reader.readAsDataURL(file);
}
</script>
</html>