这里的核心是 new FileReader(). 不知道这个API的可以去百度一下。
css部分:
.lccid {
overflow: hidden;
display: inline-block;
width: 100%;
height: 250px;
background: #4e4eec;
color: #fff;
font-size: 16px;
position: relative;
border-radius: 4px;
text-decoration: none;
text-indent: 0;
margin: 10px 0;
}
.file {
position: absolute;
width: 100%;
height: 100%;
right: 0;
top: 0;
opacity: 0;
}
.lccid>img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
}
.title {
color: #FFF;
padding: 0;
width: 100%;
position: absolute;
left: 0;
top: 50%;
margin: -30px 0 0 0;
letter-spacing: 2px;
font-size: 16px;
text-align: center;
}
HTML部分:
<div class="lccid">
<p class="title">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
行驶证</p>
<img src="" / class="img">
<input type="file" class="file" placeholder="ICCID" accept="image/*" capture="camera">
</div>
JS部分:
$(".lccid").on("change", "input[type=file]", function() {
$(this).prev().css("opacity","1")
var filePath = $(this).val();//读取图片路径
var fr = new FileReader();//创建new FileReader()对象
var imgObj = this.files[0];//获取图片
fr.readAsDataURL(imgObj);//将图片读取为DataURL
var obj = $(this).prev()[0];//
if(filePath.indexOf("jpg") != -1 || filePath.indexOf("JPG") != -1 || filePath.indexOf("PNG") != -1 || filePath.indexOf("png") != -1) {
var arr = filePath.split('\\');
var fileName = arr[arr.length - 1];
$(this).parent().next().show();
fr.onload = function() {
obj.src = this.result;
};
} else {
$(this).parent().next().show();
$(this).parent().next().children("i").html("您未上传文件,或者您上传文件类型有误!").css("color", "red");
//$(this).parent().next().html("您未上传文件,或者您上传文件类型有误!").css("color","red");
return false
}
});
如此就可以在前端页面展示出来了 ,效果图