首页 > Web开发 > 详细

上传图片在前台预览

时间:2016-06-24 12:40:14      阅读:168      评论:0      收藏:0      [点我收藏+]

前端做做图片上传功能时,经常想上传完后可以直接预览,这时候通常有两种方式,一种就是转成base64编码,然后展示出来。

document.getElementById(file).onchange = function(){
        var reader = new FileReader();
        reader.readAsDataURL(this.files[0]);
        reader.onload = function(e) {
            document.getElementById(img).src = e.target.result;
        }
    }    

 

当然还有另外一种方式,那就是用getObjectURL实现:

function getObjectURL(file) {
        var url = null;
        if (window.createObjectURL != undefined) {
            url = window.createObjectURL(file);
        } else if (window.URL != undefined) {
            url = window.URL.createObjectURL(file);
        } else if (window.webkitURL != undefined) {
            url = window.webkitURL.createObjectURL(file);
        }
        return url;
    }
document.getElementById(file).onchange = function(){
    document.getElementById(‘img‘).src = getObjectURL(this.files[0]);
}    

兼容性都不好只能兼容到IE10

上传图片在前台预览

原文:http://www.cnblogs.com/bruce-gou/p/5613623.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!