Home Web Front-end JS Tutorial JavaScript implements image preview and upload (compatible with IE) code sharing

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

Mar 23, 2017 pm 04:13 PM

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

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!

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

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to upload lyrics to QQ Music How to upload lyrics to QQ Music Feb 23, 2024 pm 11:45 PM

With the advent of the digital age, music platforms have become one of the main ways for people to obtain music. However, sometimes when we listen to songs, we find that there are no lyrics, which is very disturbing. Many people hope that lyrics can be displayed when listening to songs to better understand the content and emotions of the songs. QQ Music, as one of the largest music platforms in China, also provides users with the function of uploading lyrics, so that users can better enjoy music and feel the connotation of the songs. The following will introduce how to upload lyrics on QQ Music. first

Simple steps to upload your own music on Kugou Simple steps to upload your own music on Kugou Mar 25, 2024 pm 10:56 PM

1. Open Kugou Music and click on your profile picture. 2. Click the settings icon in the upper right corner. 3. Click [Upload Music Works]. 4. Click [Upload Works]. 5. Select the song and click [Next]. 6. Finally, click [Upload].

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to improve computer upload speed How to improve computer upload speed Jan 15, 2024 pm 06:51 PM

Upload speed becomes very slow? I believe this is a problem that many friends will encounter when uploading things on their computers. If the network is unstable when using a computer to transfer files, the upload speed will be very slow. So how can I increase the network upload speed? Below, the editor will tell you how to solve the problem of slow computer upload speed. When it comes to network speed, we all know that the speed of opening web pages, download speed, and upload speed are also very critical. Especially some users often need to upload files to the network disk, so a fast upload speed will undoubtedly save you a lot of money. Less time, what should I do if the upload speed is slow? Below, the editor brings you pictures and texts on how to deal with slow computer upload speeds. How to solve the problem of slow computer upload speed? Click "Start--Run" or "Window key"

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

See all articles