js实现上传图片本地预览功能以及限制图片的文件大小和尺寸大小

方法一:

js:

/**
     * 上传图片本地预览方法
     * @param {Object} fileObj 上传文件file的id元素  fresh-fileToUpload
     * @param {Object} previewObj 预览图片的父层id元素  fresh-send-preview-imgvideo
     * @param {Number} maxWidth 预览图最大宽  
     * @param {Number} minWidth 预览图最小宽  
     */
    fs.setImagePreview =function(fileObj, previewObj, maxWidth, minWidth) {
          var docObj = document.getElementById(fileObj);
          var imgObjPreview = document.getElementById(previewObj);

if (docObj.files && docObj.files[0]) {
              //火狐下,直接设img属性
              //火狐7以上版本不能用上面的getAsDataURL()方式获取,需要一下方式
              imgObjPreview.innerHTML ='<img id="fresh-send-preview-img"><i class="fresh-preview-close"></i>';
              var img = document.getElementById('fresh-send-preview-img');
              img.src = window.URL.createObjectURL(docObj.files[0]);
          } else {
              //IE下,使用滤镜
              try {
                  var sFilter='filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="';
                  docObj.select();
                  imgObjPreview.focus();//防止在ie9下拒绝访问,解决办法是让其他的div元素获取焦点
                  var imgSrc = document.selection.createRange().text;
                  imgObjPreview.innerHTML ='<img id="fresh-send-preview-img"><i class="fresh-preview-close"></i>';
                  var img = document.getElementById('fresh-send-preview-img');
                  img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = imgSrc;
                  //var rate = (maxWidth/img.height>maxWidth/img.width?maxWidth/img.width:maxHeight/img.height);
                  //等比例缩放图片的大小
                  var rate = (img.offsetWidth>maxWidth)?(maxWidth/img.offsetWidth):(img.offsetWidth>minWidth?1:minWidth/img.offsetWidth);
                  imgObjPreview.innerHTML = "<div id='fresh-send-preview-img' style='width:"+img.offsetWidth*rate+"px;height:"+img.offsetHeight*rate+"px;"+sFilter+imgSrc+"\"'></div><i class='fresh-preview-close'></i>";
              } catch (e) {
                  alert("您上传的图片格式不正确,请重新选择!");
                  return false;
              }
              //document.selection.empty();
          }
          //return true;
    }

使用方法:

/**
     * 发布新鲜事图片上传方法
     * @param  {string} dom 任意子节点
     */
    fs.fileupload = function(dom) {
        var that =$(dom);
        if( that.length == 0 ){
          return false;
        }
        if(that.val() == ''){
          return false;
        }
        if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(dom.value)) {
            alert('图片格式无效!');
            return false;
        }
        //显示图片预览区域
        $('#fresh-send-preview').removeClass('hiding');
        $('.fresh-send-preview-imgvideo').find('img').attr('src', 'http://img04.xesimg.com/loading.gif');
        this.setImagePreview('fresh-fileToUpload', 'fresh-send-preview-imgvideo',120, 36);
    };

html:

<div class="fresh-send-preview hide" id="fresh-send-preview">
             <div class="fresh-send-preview-imgvideo" id="fresh-send-preview-imgvideo">
                 <img id="fresh-send-preview-img" src="img/fresh-send-img.png">
                 <i class="fresh-preview-close"></i>
             </div>
</div>

<div class="fresh-send-upload">
   <input class="fresh-fileToUpload" id="fresh-fileToUpload" type="file" size="45"  name="dynImg" accept="image/*" />
 </div>

添加知识点:

如果需要删除预览图片,然后重新上传的话,需要清空file的值,最好的方法是重新赋予相同的file html文件,一边兼容各个浏览器清值的方法不同

//点击关闭图片区域按钮

$('body').off('click', '.fresh-send-box .fresh-preview-close').on('click', '.fresh-send-box .fresh-preview-close', function(){
            //删除图片同时清空file的值。以防再次上传同一张图片的时候change不改变无法正常运行
           
$('.fresh-send-upload').html('<input class="fresh-fileToUpload"
id="fresh-fileToUpload" type="file" size="45" autocomplete="off" 
name="dynImg" accept="image/*" />')
            $('#fresh-send-preview').addClass('hiding');
});

方法二:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
<title>图片上传本地预览</title>     
<style type="text/css">
#preview{width:260px;height:190px;border:1px solid #000;overflow:hidden;}
#imghead {filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=image);}
</style>
<script type="text/javascript">

//图片上传预览    IE是用了滤镜。
        function previewImage(file)
        {
          var MAXWIDTH  = 260;
          var MAXHEIGHT = 180;
          var div = document.getElementById('preview');
          if (file.files && file.files[0])
          {
              div.innerHTML ='<img id=imghead>';
              var img = document.getElementById('imghead');
              img.onload = function(){
                var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
                img.width  =  rect.width;
                img.height =  rect.height;
//                 img.style.marginLeft = rect.left+'px';
                img.style.marginTop = rect.top+'px';
              }
              var reader = new FileReader();
              reader.onload = function(evt){img.src = evt.target.result;}
              reader.readAsDataURL(file.files[0]);
          }
          else //兼容IE
          {
            var sFilter='filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="';
            file.select();
            var src = document.selection.createRange().text;
            div.innerHTML = '<img id=imghead>';
            var img = document.getElementById('imghead');
            img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src;
            var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
            status =('rect:'+rect.top+','+rect.left+','+rect.width+','+rect.height);
            div.innerHTML = "<div id=divhead style='width:"+rect.width+"px;height:"+rect.height+"px;margin-top:"+rect.top+"px;"+sFilter+src+"\"'></div>";
          }
        }
        function clacImgZoomParam( maxWidth, maxHeight, width, height ){
            var param = {top:0, left:0, width:width, height:height};
            if( width>maxWidth || height>maxHeight )
            {
                rateWidth = width / maxWidth;
                rateHeight = height / maxHeight;
                
                if( rateWidth > rateHeight )
                {
                    param.width =  maxWidth;
                    param.height = Math.round(height / rateWidth);
                }else
                {
                    param.width = Math.round(width / rateHeight);
                    param.height = maxHeight;
                }
            }
            
            param.left = Math.round((maxWidth - param.width) / 2);
            param.top = Math.round((maxHeight - param.height) / 2);
            return param;
        }
</script>     
</head>     
<body>

<div id="preview">
    <img id="imghead" border=0 src="head_180.jpg" width="180" height="180" />
</div>
<input type="file" onchange="previewImage(this)" />
   
</body>     
</html>

获取上传图片文件的大小是多少k方法:

var dom = document.getElementById(fileId);//fileId是上传文件的file的id

try {

//非ie9以下的浏览器包括火狐等
    console.log(dom.files.item(0).size/1024);

var fileSize = dom.files.item(0).size/1024 +"kB";
} catch (e) {  
    try {  
        //ie9以下的浏览器包括ie9
        var img = new Image();  
        img.src = dom.value;
        img.onload =function(){
           console.log( img.fileSize/1024)
           var fileSize = dom.files.item(0).size/1024 +"kB";
        }
        img.src = dom.value;
        
    } catch (e) {  
        console.log(23)
        return -1;  
    }  
}

上一篇:linux centos 7上运行teamviewer与找不到ID问题处理办法


下一篇:Oracle+Mybatis批量插入,更新和删除