來自 :https://blog.csdn.net/qq_37041819/article/details/116597572 侵刪
?
1.引入element-ui 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:{ //圖片上傳成功的回調(diào)函數(shù) handleAvatarSuccess(res, file) { if (file.raw.isFlag && res.code == 0) { this.imageUrl = URL.createObjectURL(file.raw); this.newBanner_Form.imgUrl = res.data.url; } }, //圖片上傳前的回調(diào)函數(shù) beforeAvatarUpload(file) { const isJPG = file.type === "image/jpeg" || file.type === "image/png"; if (!isJPG) { this.$message.error("上傳頭像圖片只能是 JPG和PNG 格式!"); } //調(diào)用[限制圖片尺寸]函數(shù) this.limitFileWH(702, 285, file).then((res) => { file.isFlag = res }) return isJPG && file.isFlag; }, //限制圖片尺寸 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: '上傳文件的圖片大小不合符標(biāo)準(zhǔn),寬需要為' + E_width + 'px,高需要為' + E_height + 'px。當(dāng)前上傳圖片的寬高分別為:' + imgWidth + 'px和' + imgHight + 'px', btn: false }) return false; }); return isSize }, } 4.解決before-upload鉤子返回false時,文件仍然上傳成功的問題 如果我們在before-upload中直接返回true或者是false,那么它其實也是會上傳文件的,因為它也會觸發(fā)on-change函數(shù)。 我這里是采用在對應(yīng)的函數(shù)中返回一個promise來解決的,就像下面這樣: beforeAvatarUpload(file) { return new Promise((resolve,reject) => { const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'; if (!isJPG) { this.$message.error('上傳頭像圖片只能是 JPG和PNG 格式!'); } //調(diào)用[限制圖片尺寸]函數(shù) this.limitFileWH(702, 285, file).then((res) => { file.isFlag = res; }); if (file.isFlag) { return resolve(true); } else { return reject(false); } }) }, ———————————————— 版權(quán)聲明:本文為CSDN博主「姜天生i」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請附上原文出處鏈接及本聲明。 原文鏈接:https://blog.csdn.net/qq_37041819/article/details/116597572
?
本文摘自 :https://www.cnblogs.com/