原 html javascript 图片上传

<input type="hidden" id="boyHead" name="boyHead" value="" />
<input type="file" id="file_boyHead" style="display:none;" />
<div id="studentHead" style="padding-top:150px;letter-spacing:2px;font-size:16px; font-weight:bold; border: 1px #d3d3d3 solid; width: 155px; height:190px; text-align: center;">学生免冠1寸近照</div>
<script type="text/javascript" >
   $(function(){

      $("#studentHead").click(function(){
         $("#file_boyHead").click();
      });
      $("#file_boyHead").change(function(){
         var objUrl = getObjectURL(this.files[0]) ;
         if (objUrl) {
            $("#studentHead").css("background-image","url("+objUrl+")");
            createImg(objUrl,155,190,'boyHead');
         }
      });
   });

   //获取图片的Base64
   function getBase64Image(img) {
      var canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, img.width, img.height);
      var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
      var dataURL = canvas.toDataURL("image/"+ext);
      return dataURL;
   }

   //赋值图片的base64
   function createImg(url,width,height,targetId) {
      var image = new Image();
      image.crossOrigin = '';
      image.src = url;
      image.width = width;
      image.height = height;
      image.onload = function(){
         var base64 = getBase64Image(image);
         document.getElementById(targetId).value = base64;
      }
      return image;
   }

   //获取图片地址(预览)
   function getObjectURL(file) {
      var url = null ;
      if (window.createObjectURL!=undefined) { // basic
         url = window.createObjectURL(file) ;
      } else if (window.URL!=undefined) { // mozilla(firefox)
         url = window.URL.createObjectURL(file) ;
      } else if (window.webkitURL!=undefined) { // webkit or chrome
         url = window.webkitURL.createObjectURL(file) ;
      }
      return url ;
   }
</script>

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注