上传图片动态预览(兼容主流浏览器)

做这个功能初始目的是为了在提交编辑前先查看效果,当然仅限于图片。

核心代码来源于网上,经测验有效

假设HTML如下:

<body>
    <img src="#" id="logo" alt="上传的图片">
    <input type="file" accept="image/*" id="upload" />
</body>

JS如下:

document.getElementById("upload").onchange = function(){
    var objUrl = getObjectURL(this.files[0]) ;
    if (objUrl) {
        document.getElementById("logo").setAttribute("src", objUrl) ;
    }
};
//建立一個可存取到該file的url
function getObjectURL(file) {
    var url = null ; 
    if (window.createObjectURL!=undefined) { // basic
        url = window.createObjectURL(file) ;
    } else if (window.URL!=undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file) ;
    } else if (window.webkitURL!=undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file) ;
    }
    return url ;
 }


原文地址:https://www.cnblogs.com/sysuzjz/p/4289312.html