有没有办法在将图片上传到服务器之前在 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
}
下面有用的引用链接:
Compatibility tables for support of HTML5, CSS3, SVG and more in desktop and mobile browsers
关于javascript - 上传前预览图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20627954/