js实现图片上传预览功能,使用base64编码来实现

实现图片上传的方法有很多,这里我们介绍比较简单的一种,使用base64对图片信息进行编码,然后直接将图片的base64信息存到数据库。

但是对于系统中需要上传的图片较多时并不建议采用这种方式,我们一般会选择存图片路径的方式,这样有助于减小数据库压力,base64

编码后的图片信息是一个很长的字符串,一般我们使用longText类型来将其存入数据库。

html代码如下:

<div class="col-sm-6">
  <img id="headPortraitImgShow" src="img/defaultHeadPoint.jpg" alt="" width="160px" height="180px" />
  <input type="file" id="headPortraitUpload" style="margin-top:10px;">
</div>

javaScript代码如下:

$("#headPortraitUpload").on("change",headPortraitListener);

 /*定义全局变量存贮图片信息*/
 var base64head="";

/*头像上传监听*/
function headPortraitListener(e) {
    var img = document.getElementById('headPortraitImgShow');
      if(window.FileReader) {
          var file  = e.target.files[0];
          var reader = new FileReader();
          if (file && file.type.match('image.*')) {
              reader.readAsDataURL(file);
          } else {
              img.css('display', 'none');
              img.attr('src', '');
          }
          reader.onloadend = function (e) {
          img.setAttribute('src', reader.result);
          base64head = reader.result;
        }
      }
}

效果预览:默认图片-----》效果图

      

最后,将base64head提交到后台存入数据库即可,下次从数据库取出直接将该base64信息放到img标签的src里面图片就回显出来了

原文地址:https://www.cnblogs.com/ynxrsoft/p/7434693.html