开心每一天1111
曾经写过的一个方法,看能不能用,有些es6的语法可以抽掉。let uploadImg = () => { let filechooser = $('.filechooser'); //点击上传的容器,因为我这里多个 // 200 KB 对应的字节数 const maxsize = 200 * 1024; filechooser.each(function(i, item){ $(item).on('change',function(){ //调用change方法 let file = this.files[0]; let _this = this; // 接受 jpeg, jpg, png 类型的图片 if (!/\/(?:jpeg|jpg|png)/i.test(file.type)) return; var reader = new FileReader(); reader.onload = function() { var result = this.result; //License = result; var img = new Image(); // 如果图片小于 200kb,不压缩 if (result.length <= maxsize) { toPreviewer(_this,result,i); return; } img.onload = function() { var compressedDataUrl = compress(img, file.type); //License_back = compressedDataUrl; toPreviewer(_this,compressedDataUrl,i); img = null; }; img.src = result; }; reader.readAsDataURL(file); }); }); //预览 let toPreviewer = (_this,dataUrl,i) => { console.log(dataUrl); }; let compress = (img, fileType) => { var canvas = document.createElement("canvas"); var ctx = canvas.getContext('2d'); var width = img.width; var height = img.height; canvas.width = width; canvas.height = height; ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.drawImage(img, 0, 0, width, height); // 压缩 var base64data = canvas.toDataURL(fileType, 0.75); canvas = ctx = null; return base64data; };};export default uploadImg;