上传图片在前台预览

前端做做图片上传功能时,经常想上传完后可以直接预览,这时候通常有两种方式,一种就是转成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

图片上传预览插件地址可兼容IE8

图片裁剪插件兼容到IE9

原文地址:https://www.cnblogs.com/bruce-gou/p/5613623.html