图片上传并显示(兼容ie),图片大小判断

  • A+
所属分类:JavaScript

HTML:

<div id="swf" style="margin: 0 auto;text-align: center;">
    <img src="/assets/img/default.jpg" alt="图片上传并显示(兼容ie),图片大小判断" height="180px" width="180px"
         id="logoshow">
</div>
<div id="headview" style="text-align: center;margin: 0 auto;">
    <input type="file" id="logo" name="logo" style="width: 180px;"
           onchange="previewImage(this)">
</div>

JS:

function previewImage(file){
    var div = document.getElementById('swf');
    if (file.files && file.files[0]) {//HTML5
        var img = document.getElementById('logoshow');
        var reader = new FileReader();
        reader.readAsDataURL(file.files[0]);
        reader.onload = function (evt) {
            img.src = evt.target.result;
            img.style.width= "180px";
        };
    }
    else //兼容IE,滤镜
    {
        alert("filter");
        var sFilter = 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="';
        file.select();
        file.blur();
        var src = document.selection.createRange().text;
        var img = document.getElementById('logoshow');
        img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src;
        div.innerHTML = "<img id=logoshow style='margin:0px auto;width:180px;height:180px;" + sFilter + src + ""'>";
    }
}

JS 判断文件大小:

<input id="file" type="file" onchange="filefujianChange(document.getElementById('file'))">

<script type="text/javascript">
    function filefujianChange(target) {
        var fileSize = 0;         
        if (!target.files) {     
            var filePath = target.value;     
            var fileSystem = new ActiveXObject("Scripting.FileSystemObject");        
            var file = fileSystem.GetFile (filePath);     
            fileSize = file.Size;    
        } else {    
            fileSize = target.files[0].size;     
        }   
        var size = fileSize / 1024;
        alert(size);    
        if(size>2000){  
            alert("附件不能大于2M");
            target.value="";
            return
        }
        var name=target.value;
        var fileName = name.substring(name.lastIndexOf(".")+1).toLowerCase();
        alert(fileName);
        if(fileName !="jpg" && fileName !="jpeg" && fileName !="pdf" && fileName !="png" && fileName !="dwg" && fileName !="gif" ){
            alert("请选择图片格式文件上传(jpg,png,gif,dwg,pdf,gif等)!");
            target.value="";
            return ;
        }
    }
</script>

 

weinxin
我的微信
爱生活、爱学习的小伙伴可以通过扫一扫二维码添加我的个人微信一起交流!
青青子衿

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: