网页需要实现上传图片,上传显示图片和路径
Html代码端
<div class="row">
<div class="col-lg-10" id="img">
<div id="imgPreview">
<img src="#" id="cropedBigImg" />
</div>
<span class="font-13 text-muted">图片文件大小不超过<font color="#727cf5">1MB</font>,格式支持<font color="#727cf5">jpg,jpeg,gif,png,bmp, video,MP4</font></span>
<div id="upImg">
<input type="file" name="file" id="chooseImage" value="文件上传" />
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="txtUrl">广告URL</label>
<input type="text" id="txtUrl" name="inputFields" class="form-control form-control-light" readonly>
</div>
</div>
</div>
CSS端,添加小样式
<style>
#imgPreview {
width: 150px;
height: 200px;
left: 10px;
top: 10px;
}
#cropedBigImg {
width: 100%;
height: 100%;
display: none;
}
</style>
js代码端
$('#chooseImage').on('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(/.jpg|.png|.gif|.bmp|.jpeg|.zip|.rar|.7z|.pdf|.doc|.docx|.xls|.xlsx|.avi|.mp4|.rmvb|.wmv|.txt|.pub|.pptx|.ppt/)) {
error_prompt_alert('上传错误,文件格式必须为:png/jpg/jpeg');
return;
} else {
$('#cropedBigImg').css('display', 'block');
$('#cropedBigImg').attr('src', src); //显示图片
$("#txtUrl").val(filePath); //显示图片的路径
}
});
效果图
选择前的样子
选择后的样子