layui的upload上传前压缩一下图片
编辑时间:2019-06-02 作者:金满斗 浏览量:3753 来源:原创

别人的,我转载的,废话不说,直接上代码。

html 


<div>
<button type="button" class="layui-btn" id="up_pic_btn">上传图片</button>
<input type="button" id = "btnHide" class="none"> <!-- 用于模拟自动上传-->
</div>


上传部分代码示例



layui.config({
   version: "{:ver()}",
   base: '/Public/layui/src/lay/'
}).extend({
   photoZip: 'plug/photoZip',
}).use(['upload', 'photoZip'], function () {
   var upload = layui.upload;
   var photoZip = layui.photoZip;
   var uploadInst = upload.render({
           elem: '#up_pic_btn',
           accept: 'file',
           exts: 'jpg|jpge|gif|png',
           size: 1024 * 10,
           url: '//upload-z2.qiniup.com/',
           uptoken_url: layfun.config.hostService + 'service/uptoken.html',
           auto: false,
           bindAction: "#btnHide",
           multiple: true,
           choose: function (obj) {
               var files = this.files = obj.pushFile();
               var oindex,
               indexArr = [];
               for (oindex in files) {
                   indexArr.push(oindex);
               };
               eindex = 0;
               star = 0;
               var len = indexArr.length;
               obj.preview(function (index, file, result) {
                   try {
                       if (file.size > 800 * 1024) {
                           (star == 0) && layer.msg("照片压缩中...", {
                               time: false
                           }, star = 1);
                           photoZip.photoCompress(file, {
                               quality: 0.9,
                               width: 1200
                           }, function (base64Codes) {
                               delete files[index];
                               obj.resetFile(index, photoZip.convertBase64UrlToBlob(base64Codes), file.name);
                               eindex++;
                               console.log(eindex);
                               console.log(len);
                               if (eindex == len) {
                                   layer.msg("全部照片已经压缩成功", function () {
                                       layer.msg("开始上传...", {
                                           time: false
                                       });
                                       $("#btnHide").trigger("click");
                                   });
                               }
                           });
                       }
                   } catch (e) {
                       layer.msg("全部照片已经压缩成功", function () {
                           layer.msg("开始上传...", {
                               time: false
                           });
                           $("#btnHide").trigger("click");
                       });
                   }
               })
           },
           before: function (obj) {
               !filelist.list && (filelist.list = []);
           },
           allDone: function (obj) {
               layfun.plupostdatatoqiniu(JSON.stringify(filelist), filekey, layfun.config.backname).then(function (res) {
                   pagelist.setdrarp();
                   layer.msg("上传成功...", {
                       time: 500
                   })
               })
           },
           done: function (res, index, upload) {
               delete this.files[index];
               filelist.list.push({
                   id: (new Date()).getTime(),
                   tmbPath: layfun.config.fileHost + res.key,
                   key: res.key,
                   usetime: 0
               })
           }
       });
});

模块代码


layui.define(function (exports) {
    var photoZip = {
        photoCompress: function (file, w, objDiv) {
            var ready = new FileReader();
            /*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
            ready.readAsDataURL(file);
            ready.onload = function () {
                var re = this.result;
                photoZip.canvasDataURL(re, w, objDiv);
            }
        },
        canvasDataURL: function (path, obj, callback) {

            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.5; // 默认图片质量为0.7
                //生成canvas
                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;
                }
                // quality值越小,所绘制出的图像越模糊
                var base64 = canvas.toDataURL('image/jpeg', quality);
                // 回调函数返回base64的值
                callback(base64);
            }
        },
        convertBase64UrlToBlob: function (urlData) {
            var arr = urlData.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], {
                type: mime
            });
        }
    };
    exports('photoZip', photoZip)
})


文章转自:https://www.cnblogs.com/blogs-8888/p/9547062.html



来说两句吧