javascript Image Preview and Upload (IE compatible)

  • 2021-08-03 09:12:05
  • OfStack

In this article, we share the specific code of preview and upload of js pictures for your reference. The specific contents are as follows


var dailiApply = {

   change: function (evt) {
    evt.preventDefault();
    var pic = document.getElementById("preview"),
     file = document.getElementById("f");

    var ext=file.value.substring(file.value.lastIndexOf(".")+1).toLowerCase();
    // gif In IE The browser is temporarily unable to display 
    if(ext!='png'&&ext!='jpg'&&ext!='jpeg'){
     alert(" The format of the picture must be png Or jpg Or jpeg Format! ");
     return;
    }
    var isIE = navigator.userAgent.match(/MSIE/)!= null,
     isIE6 = navigator.userAgent.match(/MSIE 6.0/)!= null;

    if(isIE) {
     file.select();
     var reallocalpath = document.selection.createRange().text;

     // IE6 Browser settings img Adj. src You can display pictures directly for the local path 
     if (isIE6) {
      pic.src = reallocalpath;
     }else {
      //  Non IE6 Version of IE Set directly due to security issues img Adj. src Unable to display local pictures, but it can be done through filters 
      pic.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='image',src=\"" + reallocalpath + "\")";
      //  Settings img Adj. src For base64 Coded transparent picture   Undisplay browser default pictures 
      pic.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';
     }
    }else {
     var file_arr = file.files;
     var ul = $(".weui_uploader_files");
     if(file_arr.length < 7) {
      for(var key in file_arr) {
       if(file_arr.hasOwnProperty(key)) {
        var f = file_arr[key];
        var url = URL.createObjectURL(f);
        var reader = new FileReader();
        console.log(f);
        reader.readAsDataURL(f);
        n +=1;
        if(n < 7) {
         reader._onload = function(e) {

          //  Splice displays the preview picture html
          var list = $("<li class='weui_uploader_file' style='position: relative'>" +
           "<img id='preview" + n + "' class=preview_li' style='width: 100%;height: 100%'>" +
           "<span id='delImg" + n+ "' style='position: absolute; top: 0; right: 4px; color: #e4007f'>X</span></li>");
          ul.append(list);
          //  Put the converted picture address in the img Medium 
          var pic = document.getElementById('preview' + n);
          //pic.src = this.result;
          pic.src=url;
          dailiApply.compress(f, .7,undefined);
          //images.push(f);
          document.getElementById('delImg' + n).addEventListener("click", function () {
           $(this).parent().remove();
           --n;
          });

         };
         reader._onload();
        }else {
         $.alert(" Upload at most 6 A picture ");
         n = 6;
        }
       }
      }
     }else {
      $.alert(" Upload at most 6 A picture ");
     }
    }
    return false;
   },
   /**
    * @param {Object} f input Selected pictures   Required 
    * @param {String} quality   Quality of picture compression [0, 1]
    * @param {String} output_img_type   Type of output picture 
    */
   compress: function (f, quality, output_img_type) {
    var mime_type = "image/jpeg";
    if(output_img_type!=undefined && output_img_type=="image/png"){
     mime_type = "image/png";
    }
    createImageBitmap(f).then(function(imageBitmap) {
     var max = 1000; //  Set the maximum resolution 
     var c_w = '';
     var c_h = '';
     var width = imageBitmap.width;
     var height = imageBitmap.height;
     //  Equal scaling 
     if (width > max || height > max) {
      if (width > height) {
       c_w = max;
       c_h = max * height / width;
      } else {
       c_h = max;
       c_w = max * width / height;
      }
     }else {  //  Non-scaling 
      c_w = width;
      c_h = height;
     }

     var canvas = document.createElement('canvas');
     canvas.width = c_w;
     canvas.height = c_h;
     var ctx = canvas.getContext('2d');
     ctx.drawImage(imageBitmap,0,0, width, height, 0, 0, c_w, c_h);
     canvas.toBlob(function(blob){
      images.push(blob);
     },mime_type, quality);
    });
   },
   submit: function () {
    var content = $(".weui_textarea").val().trim();
    var xhr = new XMLHttpRequest();
    var fd = new FormData(document.getElementById('uploadForm'));
    $.each(images,function(i,e){
     fd.append("images", e);
    });
    fd.append("remark", content);
    fd.append("substationproxyId", 8);
    console.log(images);
    console.log(fd);
    if(content) {
     $.ajax({
      url: CONFIG.API.addSubProxyRecruit,
      type: "POST",
      data: fd,

      processData: false, // tell jQuery not to process the data
      contentType: false, // tell jQuery not to set contentType
      beforeSend: function (xhr) {
       $.showLoading();
       $(this).prop("disabled", true)
      },
      success: function (json) {
       console.log(json);
       $.hideLoading();
       $(this).prop("disabled", false);
       if(json.errorCode == 0) {
        $.alert(" Save successfully ", function () {
         location.reload();
        })
       }else if(json.errorCode == "-101") {
        $.alert(' Error: ' +json.message, function () {
         location.href = CONFIG.HTML.login;
        });
       }else {
        $.alert(json.message, function () {

        })
       }
      }
     });
    }else {
     $.alert(' Please enter content ');
    }

   }

  };

Related articles: