首页 > 技术文章 > 单图上传预览

zhangzhongran 2017-03-22 16:59 原文

//html部分
<div class="">
    <label class="col-sm-2 control-label">活动图片</label>
    <div class="col-sm-9">
        <img  id="img0" style="width: 100px;height: 100px" src=""><input type="file" name="file" id="file0" /><span style='color:red' id="span_flie0"></span>
    </div>
</div>

 

//JS部分
<script>
    //jquery上传图片前预览
$("#file0").change(function(){
        var objUrl = getObjectURL(this.files[0]) ;
        console.log("objUrl = "+objUrl) ;
        if (objUrl) {
            $("#img0").attr("src", objUrl) ;
        }
    }) ;
    //建立一個可存取到該fileurl
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 ;
    }
</script>

推荐阅读