JS图片多个上传,并压缩为Base64 - 跑着的小强 - 博客园

来源: JS图片多个上传,并压缩为Base64 – 跑着的小强 – 博客园

首先是JS 批量上传

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<div id="Pic_pass">
           <p style="font-size: 20px;font-weight: bold;">请上传照片 </p>
           <p><span style="color: red">注:最多可以传3张</span></p>
           <div class="picDiv">
               <div class="addImages">
                   <input type="file" class="file" id="fileInput" multiple="" accept="image/png, image/jpeg, image/gif, image/jpg">
                   <div class="text-detail">
                       <span>+</span>
                       <p>点击上传</p>
                   </div>
               </div>
           </div>
       </div>

样式

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
.imageDiv {
          display:inline-block;
          width:160px;
          height:130px;
          -webkit-box-sizing:border-box;
          -moz-box-sizing:border-box;
          box-sizing:border-box;
          border:1px dashed darkgray;
          background:#f8f8f8;
          position:relative;
          overflow:hidden;
          margin:10px
      }
      .cover {
          position:absolute;
          z-index:1;
          top:0;
          left:0;
          width:160px;
          height:130px;
          background-color:rgba(0,0,0,.3);
          display:none;
          line-height:125px;
          text-align:center;
          cursor:pointer;
      }
      .cover .delbtn {
          color:red;
          font-size:20px;
      }
      .imageDiv:hover .cover {
          display:block;
      }
      .addImages {
          display:inline-block;
          width:160px;
          height:130px;
          -webkit-box-sizing:border-box;
          -moz-box-sizing:border-box;
          box-sizing:border-box;
          border:1px dashed darkgray;
          background:#f8f8f8;
          position:relative;
          overflow:hidden;
          margin:10px;
      }
      .text-detail {
          margin-top:40px;
          text-align:center;
      }
      .text-detail span {
          font-size:40px;
      }
      .file {
          position:absolute;
          top:0;
          left:0;
          width:160px;
          height:130px;
          opacity:0;
      }

JS代码

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
var userAgent = navigator.userAgent; //用于判断浏览器类型
         $(".file").change(function () {
             //获取选择图片的对象
             var cou = $('.imageDiv').length
             console.log(cou)
             var docObj = $(this)[0];
             var picDiv = $(this).parents(".picDiv");
             var fileList = docObj.files;
             console.log(fileList)
             console.log(fileList.length)
             console.log(picDiv)
             //循环遍历
             for (var i = 0; i < fileList.length; i++) {
                 //动态添加html元素
                 var picHtml = "<div class='imageDiv' > <img id='img" + fileList[i].name + "' /> <div class='cover'><i class='delbtn'>删除</i></div></div>";
                 picDiv.prepend(picHtml);
                 //获取图片imgi的对象
                 var imgObjPreview = document.getElementById("img" + fileList[i].name);
                 if (fileList && fileList[i]) {
                     formData.append("file", docObj.files[i]);
                     
                     //图片属性
                     imgObjPreview.style.display = 'block';
                     imgObjPreview.style.width = '160px';
                     imgObjPreview.style.height = '130px';
                     //imgObjPreview.src = docObj.files[0].getAsDataURL();
                     //火狐7以上版本不能用上面的getAsDataURL()方式获取,需要以下方式
                     if (userAgent.indexOf('MSIE') == -1) {
                         //IE以外浏览器
                         imgObjPreview.src = window.URL.createObjectURL(docObj.files[i]); //获取上传图片文件的物理路径;
                         
                         console.log(docObj.files[i]);
                         // var msgHtml = '<input type="file" id="fileInput" multiple/>';
                     else {
                         //IE浏览器
                         if (docObj.value.indexOf(",") != -1) {
                             var srcArr = docObj.value.split(",");
                             imgObjPreview.src = srcArr[i];
                             console.log(srcArr[i]);
                         else {
                             imgObjPreview.src = docObj.value;
                         }
                     }
                 }
             }
            
             $('#fliei1').click(function () {
                 console.log($(".file").files)
             })
             /*删除功能*/
             $(".delbtn").click(function () {
                 var _this = $(this);
                 _this.parents(".imageDiv").remove();
             });
         });
     })

效果

 

但是图片都是没有压缩的 、

1
 

 

本来JS 是没有办法压缩的 但是H5的画布可以 可以用画布压缩

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
   function dealImage(path, obj) {
            var img = new Image();
            img.src = path;
            img.onload = function () {
                var that = this;
                var w = that.width,
                    h = that.height,
                    scale = w / h;
                w = obj.width || w;
                h = obj.height || (w / scale);
                var quality = 0.85; //压缩质量 1是不压缩
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');
                var anw = document.createAttribute("width");
                anw.nodeValue = w;
                var anh = document.createAttribute("height");
                anh.nodeValue = h;
                canvas.setAttributeNode(anw);
                canvas.setAttributeNode(anh);
                ctx.drawImage(that, 0, 0, w, h);
                if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
                    quality = obj.quality;
                }
                var base64 = canvas.toDataURL('image/jpeg', quality);
                //最后返回压缩后的base64编码
                console.log(base64)
            }
        }
<br>
<br>              var imgReaderI = new FileReader();<br>               //转换base64编码
                        imgReaderI.readAsDataURL(docObj.files[i]);
                        console.log(imgReaderI)
                        var size=docObj.files[i].size
                        imgReaderI.onloadend = function (evt) {
                            //压缩
                                dealImage(this.result, { width: 180 });
                            }
                        }

有一点 docObj.files[i] 这个表示选择的图片可以传到后台直接保存 但是没有压缩。

 

1个1.9M 压缩过后28.2K 还是特别客观的 接下来 我们就可以吧这个字符串通过AJAX方式传入后台。进行保存或者直接放入数据库,下一篇 我会写后台保存方法MVC 保存到服务器 返回相对路径

赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏