javascript - 上传前预览图像?

标签 javascript image file-upload

有没有办法在将图片上传到服务器之前在 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/

相关文章:

python - 渲染灰度图像

reactjs - React Native 上传到 YouTube

javascript - 需要使用箭头键在搜索建议中移动

javascript - 单击按钮时不会打开提示窗口

python - PyQt5 - 每次单击按钮都会打开新的图像窗口

java - 使用 PD4ML 将 HTML 转换为带有动态图像的 PDF

javascript - 无法单击生成的元素?

javascript - 如何更改谷歌地图中选择的特定状态的颜色

php - 无限图像上传到服务器和名称、类别等和多个图像路径(1 行)到数据库

php - Amazon S3 - 您建议的上传小于允许的最小大小