Home  >  Article  >  Web Front-end  >  用HTML5轻松实现图片预览

用HTML5轻松实现图片预览

PHP中文网
PHP中文网Original
2017-03-23 16:16:334505browse

        在网页中实现图片上传功能,当用户选择了图片文件后,想在页面中即时预览该图片,这个简单的需求在很久很久以前可以实现,后来因为安全性的问题被禁止直接访问本地文件了,所以又在很长很长一段时间里,想通过HTML直接预览用户选择的图片变得不可能,自从有了HTML5,这个功能又回来了,通过FileReader可以轻松的实现这个功能。

  只要在3e701519c4bde102649c97eab49f5c17文件表单元素中监听 onchange 事件,然后通过FileReader读取图片文件,然后将读取的内容在用HTML5轻松实现图片预览中显示即可。示例代码如下:

document.getElementById('file').onchange = function(evt) {
    
// 如果浏览器不支持FileReader,则不处理
    
if
 (window.FileReader) 
return
;
    var files = evt.target.files;
    
for
 (var i = 0, f; f = files[i]; i++) {
        
if
 (!f.type.match('image.*')) {
            
continue
;
        }
        var reader = 
new
 FileReader();
        reader.onload = (function(theFile) {
            
return
 function(e) {
                
// img 元素
                document.getElementById('previewImage').src = e.target.result;
            };
        })(f);
        reader.readAsDataURL(f);
    }
}

以上就是用HTML5轻松实现图片预览的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!

相关文章:

详解html5图片上传支持图片预览压缩及进度显示兼容IE6及标准浏览器

javascript实现图片预览和上传(兼容IE)代码分享

JavaScript进阶(八)JS实现图片预览并导入服务器功能

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn