在工作中有这样的需求,在页面中通过选择图片,不通过上传服务器,并在页面中显示出来的功能;(虽说这样做很变态,选择完图片上传到服务器,通过返回的图片地址去渲染图片才是正道,但是有些时候需求就是这样,没有办法~)闲话到此,贴出代码:
document.getElementById
('selectImg').addEventListener('change',()=>{
const file = document.getElementById('selectImg');
const fileObj = file.files[0];
const windowURL = window.URL || window.webkitURL;
const img = document.getElementById('preview');
if(file && fileObj) {
const dataURl = windowURL.createObjectURL(fileObj);
img.setAttribute('src',dataURl);
}
},false)
html代码:
<input
type=
"file" id=
"selectImg" />
<img id=
"preview" />
转载请注明原文地址: https://ju.6miu.com/read-22090.html