vue.js下图片压缩压缩上传

HTML
    
JS
      // 上传图片
      onUpload: function (e) {
            var that = this;
            let file = e.target.files[0];
            if (!/image\/\w+/.test(file.type)) {
                alert("请选择图片");
                return false;
            }
            var load;
            load = $.loading({
                content: '上传中...',
            })
            // 通过canvas压缩图片
            var reader = new FileReader();
            reader.readAsDataURL(file);
            var img = new Image;
            reader.onload = function (e) {
                var width = 1080, //图像大小
                    quality = 0.8, //图像质量
                    canvas = document.createElement("canvas"),
                    drawer = canvas.getContext("2d");
                img.src = this.result;
                img.onload = function () {
                    canvas.width = width;
                    canvas.height = width * (img.height / img.width);
                    drawer.drawImage(img, 0, 0, canvas.width, canvas.height);
                    img.src = canvas.toDataURL("image/png", quality);
                }
            }
            setTimeout(function () {
                // 创建form对象
                let param = new FormData();
                // 通过append向form对象添加数据
                param.append('img', file);
                // 文件大小
                param.append('size', file.size);
                for (var n in that.params) {
                    param.append(n, that.params[n]);
                }
                // 创建ajax
                var xhr = new XMLHttpRequest();

                xhr.onload = function () {
                    var d = JSON.parse(xhr.responseText);
                    if (d.code == '0') {
                        load.loading("hide");
                        that.upImgList.push({ url: img.src, id: d.data.file_ids[0] })
                    }
                }
                xhr.open("POST", "http://192.168.1.39:27803/Common_Upload/uploadImg", true);

                // 发送表单数据
                xhr.send(param);
            }, 1000);
        },
        // base64转文件
        dataURItoBlob: function (dataURI) {
            var byteString = atob(dataURI.split(',')[1]);
            var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
            var ab = new ArrayBuffer(byteString.length);
            var ia = new Uint8Array(ab);
            for (var i = 0; i < byteString.length; i++) {
                ia[i] = byteString.charCodeAt(i);
            }
            return new Blob([ab], { type: mimeString });
        },

你可能感兴趣的:(vue.js下图片压缩压缩上传)