gpt4 book ai didi

javascript - 上传前预览图像?

转载 作者:行者123 更新时间:2023-11-30 12:52:02 24 4
gpt4 key购买 nike

有没有办法在将图片上传到服务器之前在 html 页面上预览图片?

我需要显示一张我还需要上传的图片的预览,只是为了表明已经做了更改。我可能只需要更改图像源。有没有我可以使用的现有技术/方法?

最佳答案

可以使用HTML5 FileReader API

仅使用 JavaScript 和 FileReader 对象,我们就可以让用户将图像加载到应用程序中。

HTML代码:

<input type="file" id="getimage">
<fieldset>
<legend>Your image here</legend>
<div id="imgstore"></div>
</fieldset>

JavaScript 代码:

<script>
function imageHandler(e2)
{
var store = document.getElementById('imgstore');
store.innerHTML='<img src="' + e2.target.result +'">';
}

function loadimage(e1)
{
var filename = e1.target.files[0];
var fr = new FileReader();
fr.onload = imageHandler;
fr.readAsDataURL(filename);
}

window.onload=function()
{
var x = document.getElementById("filebrowsed");
x.addEventListener('change', readfile, false);
var y = document.getElementById("getimage");
y.addEventListener('change', loadimage, false);
}
</script>

如何检查浏览器是否支持 HTML5 文件 API:

// Checking all the possible window objects needed for file api
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Browser is fully supportive.
} else {
// Browser not supported. Try normal file upload
}

下面有用的引用链接:

Demo Here

Complete Example Here

Compatibility tables for support of HTML5, CSS3, SVG and more in desktop and mobile browsers

关于javascript - 上传前预览图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20627954/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com