JavaScript实现上传图片预览[js前端实现]

时间:2023-03-09 22:24:18
JavaScript实现上传图片预览[js前端实现]
<body>
<input type="file" id="file_input" onchange="show_image()" />
<img src="" alt="" id="show_img" width="100px" height="100px" style="display: none;" />
</body>
<script>
function show_image() {
//首先获取到文件输入框和img元素
file_input = document.getElementById("file_input");
show_img = document.getElementById("show_img");
//创建URL对象
show_img.src = window.URL.createObjectURL(file_input.files[0]);
//显示图片
show_img.style.display = 'block';
}
</script>

总结一下,就是使用window.URL.createObjectURL()方法使用文件域中的文件创建一个URL对象赋值给img的src属性,即时在网页中显示出来