<template> <div> <label> 上传图片: <input type="file" id="file" accept="image/jpg, image/jpeg, image/png, image/svg, image/gif" > <br> <br> <button @click="submitPic">提交</button> <img :src="imgurl" alt="" style="100%"> </label> </div> </template> <script> export default { data() { return { imgurl:'' }; }, methods: { submitPic() { console.log(11); let _this = this; var fileObj = document.getElementById("file").files[0]; var form = new FormData(); //上传图片大于1M进行压缩 if (fileObj.size / 1024 > 1025) { console.log(22); this.photoCompress( fileObj, { quality: 0.5 }, function(base64Codes) { var bl = _this.convertBase64UrlToBlob(base64Codes); form.append("file", bl); // 文件对象 //上传 console.log(bl,99); _this.blobToDataURL(bl,res =>{ _this.imgurl = res; }) } ); } else { form.append("file", fileObj); //上传 } }, /** * @param file: 上传的图片 * @param objCompressed:压缩后的图片规格 * @param objDiv:容器或回调函数 */ photoCompress(file, objCompressed, objDiv) { let _this = this; var ready = new FileReader(); ready.readAsDataURL(file); ready.onload = function() { var fileResult = this.result; _this.canvasDataURL(fileResult, objCompressed, objDiv); }; }, canvasDataURL(path, objCompressed, callback) { var img = new Image(); img.src = path; img.onload = function() { var that = this; //默认压缩后图片规格 var quality = 0.5; var w = that.width; var h = that.height; var scale = w / h; //实际要求 w = objCompressed.width || w; h = objCompressed.height || w / scale; if ( objCompressed.quality && objCompressed.quality > 0 && objCompressed.quality <= 1 ) { quality = objCompressed.quality; } //生成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); var base64 = canvas.toDataURL("image/jpeg", quality); // 回调函数返回base64的值 callback(base64); }; }, convertBase64UrlToBlob(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 }); }, blobToDataURL(blob, callback) { var a = new FileReader(); a.onload = function (e) { callback(e.target.result); } a.readAsDataURL(blob); } } }; </script> <style lang="css" scoped> </style>