input type="file" 上传文件,显示上传图片,并替换上传按钮的位置
限制上传格式可以用 accept=" ",比如 accept=".doc,.docx" (限制上传文件为doc/docx)其他的都不可以
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.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;
}
</style>
<script src="./jquery-2.1.2.min.js"></script>
</head>
<body>
<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"> //匹配所有image的格式
</div>
<script>
$(".lccid").on("change", "input[type=file]", function() {
var fileInput = $('.file').get(0).files[0];
console.log(fileInput)
$(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
}
});
</script>
</body>
</html>