html:
<div class="aui-col-xs-3" id="img">
<div class="aui-grid-label">添加图片</div>
<div id="upImg">
<input type="file" name="file" id="chooseImage" />
</div>
<div id="imgPreview">
<img src="#" id="cropedBigImg" />
</div>
</div>
css:
#img {
float: left;
margin-left: 20px;
width: 150px;
height: 60px;
}
#upImg {
position: absolute;
top: 0px;
left: 0px;
}
#upImg input {
width: 70px;
height: 60px;
opacity: 0;
}
#imgPreview {
width: 80px;
height: 60px;
position: absolute;
left: 70px;
top: 0px;
}
#cropedBigImg{
width: 100%;
height: 100%;
display: none;
}
$(function() {
$("#chooseImage").change(function() {
//当chooseImage的值改变时,执行此函数
var filePath = $(this).val(), //获取到input的value,里面是文件的路径
fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(),
src = window.URL.createObjectURL(this.files[0]); //转成可以在本地预览的格式
// 检查是否是图片
if (!fileFormat.match(/.png|.jpg|.jpeg/)) {
alert('上传错误,文件格式必须为:png/jpg/jpeg');
return;
} else {
$(".bbDImg span").text("");
$('#cropedBigImg').css('display', 'block');
$('#cropedBigImg').attr('src', src);
}
});
})
来源:CSDN
作者:qq_38971164
链接:https://blog.csdn.net/qq_38971164/article/details/104524300