//文件上传 fileUpload(e){ let vm=this; if (e.target.files.length==0){ return false; } if(e.target.files[0].type!=='image/jpeg'&&e.target.files[0].type!=='image/png'){ this.$message.error('上传图片只能是JPG/PNG格式!'); return false } if (e.target.files[0].size/1024/1024>5){ this.$message.error('上传图片大小不超过5M'); return false } let option={file:e.target.files[0]} var reader = new FileReader(); //files[0]对象是从input type=file中获取的file对象 reader.readAsDataURL(option.file); //将file对象base64转码成功后进入 reader.onload = function () { //声明img标签,并将未压缩的图片赋值给src属性 var image = document.createElement('img') image.setAttribute('src', this.result); image.addEventListener('load', function () { var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); var originWidth = this.width; var originHeight = this.height; // 最大尺寸限制 var maxWidth = 1500 // 目标尺寸 var targetWidth = originWidth, targetHeight = originHeight; // 图片尺寸超过宽度400的限制 if (originWidth > maxWidth) { // 更宽,按照宽度限定尺寸 targetWidth = maxWidth; targetHeight = Math.round(maxWidth * (originHeight / originWidth)); } // canvas对图片进行缩放 canvas.width = targetWidth; canvas.height = targetHeight; context.drawImage(this, 0, 0, targetWidth, targetHeight); var dataBase = canvas.toDataURL(e.target.files[0].type); // 将base64转换为files对象 var arr = dataBase.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while(n--){ u8arr[n] = bstr.charCodeAt(n); } let file=new File([u8arr], e.target.files[0].type=='image/jpeg'?'img.jpg':'img.png', {type:mime}); // 将files对象压缩为二进制 let formData = new FormData(); formData.append( 'file' , file ); //ajax请求 vm.$api.upload.upload(( flag, result )=>{ if( flag ){ vm.form.Pic=result.data.Data.URL } }, formData ); }); }; }