<template>
<div>
<a href="javascript:void(0);" @change="addImage" class="a">
<input type="file" class="fileopen" />上传图片
</a>
<img :src="imgsrc" alt class="imgview" accept="image/png, image/jpeg, image/gif, image/jpg" />
</div>
</template>

<script>
export default {
data() {
return {
imgsrc: ""
};
},
methods: {
addImage() {
var input = document.querySelector("input");
//1. 拿到fileinput里面的文件, 这个file是一个file对象, file对象不能直接展示的
var file = input.files[0];

//2. 读取文件,成功img标签可以直接使用的格式
//FileReader类就是专门用来读文件的
var reader = new FileReader();
window.console.log(file);

//3. 开始读文件
//readAsDataURL: dataurl它的本质就是图片的二进制数据, 进行base64加密后形成的一个字符串, 这个字符串可以直接作用img标签的图片资源使用

reader.readAsDataURL(file);
let _this = this;
//4. 因为文件读取是一个耗时操作, 所以它在回调函数中,才能够拿到读取的结果
reader.onload = function() {
window.console.log(reader.result);
//直接使用读取的结果
_this.imgsrc = reader.result;
};
_this.imgsrc = file;
}
}
};
</script>

<style lang="less" scoped>
.imgview {
width: 150px;
height: 150px;
border-radius: 50%;
border: 1px solid red;
}
.a {
position: relative;
display: block;
text-decoration: none;
color: aqua;
}
.fileopen {
position: absolute;
left: 0;
top: 0;
opacity: 0;
filter: alpha(opacity=0);
width: 64px;
overflow: hidden;
}
</style>

  

vue预览本地图片_javascript

 

遇见问题,这是你成长的机会,如果你能够解决,这就是收获。


作者:​​晚来南风晚相识​​​