input file图片上传预览效果

两种方法,方法一:

js代码:

//头像上传预览
    $("#up").change(function() {
        var $file = $(this);
        var fileObj = $file[0];
        var windowURL = window.URL || window.webkitURL;
        var dataURL;
        var $img = $("#ImgPr");
        if(fileObj && fileObj.files && fileObj.files[0]){
        dataURL = windowURL.createObjectURL(fileObj.files[0]);
        $img.attr('src',dataURL);
        }else{
        dataURL = $file.val();
        var imgObj = document.getElementById("ImgPr");
        imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
        imgObj.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;
         
        }
    });

html:

<div class="picbtn"><img id="ImgPr" src="images/neik.png"</div>
<a class="chooseimg" href="#"><input type="file" id="up">从手机相册中选择</a>

 

原生js实现,方法二:

js代码:

function $$(obj) {
    return document.getElementById(obj);
}
function upload(f){
    
    var str = "";
    for(var i=0;i<f.length;i++){
        var reader = new FileReader();
        reader.readAsDataURL(f[i]);
        reader.onload = function(e){
            str+="<img src='"+e.target.result+"'/>";
            $$("dd").innerHTML = str;
        }
    }

}

html:

<input id="load" type="file" onchange="upload(this.files)" multiple/>
<div id="dd"></div>
multiple表示可以上传多张图片

function readAsDataURL(){  
        var file = document.getElementById("upload").files;
        var result=document.getElementById("imgcon");  
        for(i = 0; i< file.length; i ++) {
            var reader    = new FileReader();    
            reader.readAsDataURL(file[i]);  
            reader.onload=function(e){  
                //多图预览
                result.innerHTML = result.innerHTML + '<div class="img"><img src="' + this.result +'"><a class="imgclose" href="javascript:;" onclick="closeimg(this)"></a></div>';
            }
        }
    } 

 

posted @ 2016-10-13 11:42  柒叶  阅读(8354)  评论(0编辑  收藏  举报