Vue+Element ui上传图片限制图片尺寸

Vue+Element ui上传图片限制图片尺寸

1.在template中 引用el-upload组件

<el-upload class="avatar-uploader" :headers="myHeaders" :action="上传图片的地址" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
	<img v-if="imageUrl" :src="imageUrl" class="avatar" />
	<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>

2.在style中 定义el-upload的样式

<style>
  .avatar-uploader .el-upload {
     
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
     
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
     
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
     
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

​ 3.在methods里 定义限制图片的方法

methods:{
     
    //图片上传成功的回调函数
    handleAvatarSuccess(res, file) {
     
		if (file.raw.isFlag && res.code == 0) {
     
			this.imageUrl = URL.createObjectURL(file.raw);
			this.newBanner_Form.imgUrl = res.data.url;
		}
	},
    //图片上传前的回调函数
	beforeAvatarUpload(file) {
     
		const isJPG = file.type === "image/jpeg" || file.type === "image/png";
			if (!isJPG) {
     
				this.$message.error("上传头像图片只能是 JPG和PNG 格式!");
			}
        	//调用[限制图片尺寸]函数
			this.limitFileWH(702, 285, file).then((res) => {
     
				file.isFlag = res
			})
			return isJPG;
	},
	//限制图片尺寸
	limitFileWH(E_width, E_height, file) {
     
		let _this = this;
		let imgWidth = "";
		let imgHight = "";
		const isSize = new Promise(function(resolve, reject) {
     
			let width = E_width;
			let height = E_height;
			let _URL = window.URL || window.webkitURL;
			let img = new Image();
			img.onload = function() {
     
				imgWidth = img.width;
				imgHight = img.height;
				let valid = img.width == width && img.height == height;
				valid ? resolve() : reject();
			}
			img.src = _URL.createObjectURL(file);
		}).then(() => {
     
			return true;
		}, () => {
     
			_this.$message.warning({
     
			message: '上传文件的图片大小不合符标准,宽需要为' + E_width + 'px,高需要为' + E_height + 'px。当前上传图片的宽高分别为:' + imgWidth + 'px和' +
							imgHight + 'px',
			btn: false
		})
			return false;
		});
			return isSize
	},
}

你可能感兴趣的:(经验分享,vue,elementui)