前言
显示一个图片,除了直接放文件路径,还可以放Base64
当我们用file选择一个文件时,我们希望能够读取到文件路径,然后显示到一个img上
或许你会想利用value值显示,input:file上确实有value但是这个value不能用
fileReader,尽量先监听,然后再读取,好了不废话了直接看代码吧
效果图
js部分
<script>
let _input = document.querySelector('[type="file"]');
let _imgList = document.querySelector(".img-list");
let reader = new FileReader();
// 读取完成后将图片插入
reader.onload = function () {
console.log("读取完成,结果为bease64格式", this.result);
let img = new Image();
img.src = this.result;
_imgList.appendChild(img);
};
// 读取
_input.onchange = function () {
let _file = this.files[0]; //获取选中的文件
if (
_file.type === "image/png" ||
_file.type === "image/jpeg" ||
_file.type === "image/jpg"
) {
reader.readAsDataURL(_file); //读取文件
} else {
alert("格式错误");
}
};
</script>
html部分
<div class="upload">
<div class="img-list"></div>
<div class="upload-btn">
+
<!-- accept 限制文件类型 -->
<input type="file" accept=".png,.jpeg,.jpg" />
</div>
</div>
css部分
* {
box-sizing: border-box;
}
.upload-btn {
width: 100px;
height: 100px;
border: 2px solid #ccc;
text-align: center;
line-height: 88px;
font-size: 70px;
color: #ccc;
position: relative;
}
.upload-btn [type="file"] {
opacity: 0;
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
width: 100%;
height: 100%;
}
.upload {
display: flex;
align-items: center;
}
.img-list {
height: 100px;
}
.img-list img {
height: 100px;
width: 100px;
}
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行
csdn文章推荐受影响解决办法10个字10行