Home > Web Front-end > JS Tutorial > body text

JavaScript implements image preview and upload (compatible with IE) code sharing

黄舟
Release: 2017-03-23 16:13:58
Original
1428 people have browsed it

This article mainly introduces in detail the relevant information of javascript image preview and upload, which has certain reference value. Interested friends can refer to the examples of

I have shared the specific code for js image preview and upload for your reference. The specific content is 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在IE浏览器暂时无法显示
    if(ext!='png'&&ext!='jpg'&&ext!='jpeg'){
     alert("图片的格式必须为png或者jpg或者jpeg格式!");
     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浏览器设置img的src为本地路径可以直接显示图片
     if (isIE6) {
      pic.src = reallocalpath;
     }else {
      // 非IE6版本的IE由于安全问题直接设置img的src无法显示本地图片,但是可以通过滤镜来实现
      pic.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='image',src=\"" + reallocalpath + "\")";
      // 设置img的src为base64编码的透明图片 取消显示浏览器默认图片
      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) {

          // 拼接显示预览图片的html
          var list = $("<li class=&#39;weui_uploader_file&#39; style=&#39;position: relative&#39;>" +
           "<img id=&#39;preview" + n + "&#39; class=preview_li&#39; style=&#39;width: 100%;height: 100%&#39;>" +
           "<span id=&#39;delImg" + n+ "&#39; style=&#39;position: absolute; top: 0; right: 4px; color: #e4007f&#39;>X</span></li>");
          ul.append(list);
          // 将转化后的图片地址放在img中
          var pic = document.getElementById(&#39;preview&#39; + n);
          //pic.src = this.result;
          pic.src=url;
          dailiApply.compress(f, .7,undefined);
          //images.push(f);
          document.getElementById(&#39;delImg&#39; + n).addEventListener("click", function () {
           $(this).parent().remove();
           --n;
          });

         };
         reader._onload();
        }else {
         $.alert("最多上传6张图片");
         n = 6;
        }
       }
      }
     }else {
      $.alert("最多上传6张图片");
     }
    }
    return false;
   },
   /**
    * @param {Object} f input选择的图片 必填
    * @param {String} quality  图片压缩的质量[0, 1]
    * @param {String} output_img_type  输出图片的类型
    */
   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; // 设置最大分辨率
     var c_w = &#39;&#39;;
     var c_h = &#39;&#39;;
     var width = imageBitmap.width;
     var height = imageBitmap.height;
     // 等比例缩放
     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 {  // 不缩放
      c_w = width;
      c_h = height;
     }

     var canvas = document.createElement(&#39;canvas&#39;);
     canvas.width = c_w;
     canvas.height = c_h;
     var ctx = canvas.getContext(&#39;2d&#39;);
     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(&#39;uploadForm&#39;));
    $.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("保存成功", function () {
         location.reload();
        })
       }else if(json.errorCode == "-101") {
        $.alert(&#39;出错:&#39; +json.message, function () {
         location.href = CONFIG.HTML.login;
        });
       }else {
        $.alert(json.message, function () {

        })
       }
      }
     });
    }else {
     $.alert(&#39;请输入内容&#39;);
    }

   }

  };
Copy after login

Related articles:

Easily implement image preview with HTML5

Detailed explanation of html5 image upload supports image preview compression and progress display. Compatible with IE6 and standard browsers

##JavaScript Advanced (8) JS implements image preview and import server functions

The above is the detailed content of JavaScript implements image preview and upload (compatible with IE) code sharing. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!