d小旭

js实现上传图片回显功能

用到h5技术

                    <img id="headimg" src="<%=path%>/resources/images/icon4.png" style="cursor:pointer;" height="90px;" width="95%;">
                    <input id="headurladd" type="file" name="headUrl1" onchange="readFile(this)" style="display: none;" />
                    <input type="hidden" name="headUrl" id="logo" value="" />

js如下:

$("#headimg").click(function(){
    addhead('headurladd');
});
function addhead(obj){
     $("#"+obj).click();
}

function readFile(obj){
    var file = obj.files[0];
    //判断类型是不是图片  
   /*  if(!/image\/\w+/.test(file.type)){     
            alert("请确保文件为图像类型");   
            return false;
    }    */
    var reader = new FileReader();
    reader.readAsDataURL(file);

//情况一:对读取到的图片编码
    reader.onload = function(e){
        var imgBase64Data =encodeURIComponent(e.target.result);  
        $("#headimg")[0].src=this.result;
         var res = (this.result);
         var pos = imgBase64Data.indexOf("4")+4;
         imgBase64Data = imgBase64Data.substring(pos);
         $('#logo').val(imgBase64Data);
    } 

//情况二:对读取的图片没编码

    reader.onload = function(e){
        var imgBase64Data = e.target.result;
        $("#headimg")[0].src=this.result;
         var res = (this.result);
         var pos = imgBase64Data.indexOf("4")+2;
         imgBase64Data = imgBase64Data.substring(pos);
         $('#logo').val(imgBase64Data);
    }
}

 

posted on 2017-03-31 16:11  d小旭  阅读(6337)  评论(0编辑  收藏  举报

导航