怎么在js 里面限制上传图片的大小不能超过 1M?

JavaScript012

怎么在js 里面限制上传图片的大小不能超过 1M?,第1张

这样设置的:

1、先用form标签创建一个上传的表单。

<form id="form1" name="form1" method="post" action="" enctype="multipart/form-data">

 <p><input type="hidden" name="MAX_FILE_SIZE" value="100000" /></p>

 <p><input name="userfile" id="userfile" type="file" onchange="check()"/></p>

</form>

2、用Javascript设置格式和大小。

<script language="JavaScript" type="text/javascript">  function check()    {var aa=document.getElementById("userfile").value.toLowerCase().split('.')//以“.”分隔上传文件字符串   // var aa=document.form1.userfile.value.toLowerCase().split('.')//以“.”分隔上传文件字符串           if(document.form1.userfile.value=="")    {        alert('图片不能为空!')        return false    }    else    {    if(aa[aa.length-1]=='gif'||aa[aa.length-1]=='jpg'||aa[aa.length-1]=='bmp'

||aa[aa.length-1]=='png'||aa[aa.length-1]=='jpeg')//判断图片格式    {var imagSize =  document.getElementById("userfile").files[0].sizealert("图片大小:"+imagSize+"B")if(imagSize<1024*1024*1)        alert("图片大小在1M以内,为:"+imagSize/(1024*1024)+"M")        return true    }    else    {        alert('请选择格式为*.jpg、*.gif、*.bmp、*.png、*.jpeg 的图片')//       return false    }    }    }  </script>

图片超过1M则不能上传 如图:

js版和css版自动按比例调整图片大小方法,分别如下:

<title>javascript图片大小处理函数</title>

<script language=Javascript>

var proMaxHeight = 150

var proMaxWidth = 110

function proDownImage(ImgD){

      var image=new Image()

      image.src=ImgD.src

      if(image.width>0 && image.height>0){

      var rate = (proMaxWidth/image.width < proMaxHeight/image.height)?proMaxWidth/image.width:proMaxHeight/image.height

    if(rate <= 1){   

     ImgD.width = image.width*rate

     ImgD.height =image.height*rate

    }

    else {

                          ImgD.width = image.width

                          ImgD.height =image.height

                  }

      }

}

</script>

</head>

<body>

<img src="999.jpg" border=0 width="150" height="110"  onload=proDownImage(this)   />

<img src="room.jpg" border=0 width="150" height="110" onload=proDownImage(this)   />

</body>

纯css的防止图片撑破页面的代码,图片会自动按比例缩小:

<style type="text/css">

.content-width {MARGIN: autoWIDTH: 600px}

.content-width img{MAX-WIDTH: 100%!importantHEIGHT: auto!importantwidth:expression(this.width > 600 ? "600px" : this.width)!important}

</style>

<div class="content-width">

  <p><img src="/down/js/images/12567247980.jpg"/></p>

  <p><img src="/down/js/images/12567247981.jpg"/></p>

</div>

图片按比例缩放

function DrawImage(Img,WIDTH,HEIGHT){

var image=new Image()

image.src=Img.src

width=WIDTH//预先设置的所期望的宽的值

height=HEIGHT//预先设置的所期望的高的值

if(image.width>width||image.height>height){//现有图片只有宽或高超了预设值就进行js控制

w=image.width/width

h=image.height/height

if(w>h){//比值比较大==>宽比高大

//定下宽度为width的宽度

Img.width=width

//以下为计算高度

Img.height=image.height/w

}else{//高比宽大

//定下宽度为height高度

img.height=height

//以下为计算高度

Img.width=image.width/h

}

}

}

<img src="xxxx" onload=javascript:DrawImage(this,290,215)>