圖片上傳前預(yù)覽需求
很多業(yè)務(wù)場景下员萍,我們需要在用戶上傳圖片前,先預(yù)覽待上傳的圖片
<body>
<input type="file">
<img src="" alt="">
</body>
</html>
<script>
const ipt = document.querySelector('input')
const img = document.querySelector('img')
ipt.addEventListener('change', (event) => {
// 獲取當(dāng)前圖片信息
let file = event.target.files[0]
const reader = new FileReader()
// 轉(zhuǎn)化使用bese64格式
reader.readAsDataURL(file)
// 成功后的回調(diào)
reader.onload = function () {
img.setAttribute('src',this.result)
}
})
</script>