search
HomeWeb Front-endJS TutorialJavaScript implements image preview and upload (compatible with IE) code sharing

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; alt="JavaScript implements image preview and upload (compatible with IE) code sharing" >" +
           "<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;);
    }

   }

  };

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!

Statement
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.