template部分代碼,引入upload組件,這里采用自動上傳文件
<div class="filesC">
<el-upload
ref="files"
name="imgFile"
class="avatar-uploader"
:with-credentials="true"
:action="action"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:on-error="handleAvatarError"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
圖片尺寸:141*54
</div>
script部分代碼,圖片上傳之前觸發 beforeAvatarUpload ,在這里return false 會中斷上傳操作
beforeAvatarUpload (file) {
let _this = this
if (file.type.indexOf('image')<0) {
this.$alert({message: '圖片格式不正確', btn: false})
return false
}
const isLt2M = file.size / 1024 / 1024 < 2;
const isSize = new Promise(function(resolve, reject) {
let width = 141;
let height = 54;
let _URL = window.URL || window.webkitURL;
let img = new Image();
img.onload = function() {
let valid = img.width == width && img.height == height;
valid ? resolve() : reject();
}
img.src = _URL.createObjectURL(file);
}).then(() => {
return file;
}, () => {
_this.$alert({message: '上傳的icon必須是等於141*54!', btn: false})
return Promise.reject();
});
return isSize
},
handleAvatarSuccess (res, file) {
if (res.state==200) {
this.imageUrl = URL.createObjectURL(file.raw);//從文件中讀取的本地文件路徑,用於顯示在img標簽里
this.fileUrl = res.data//上傳成功后,后台給返回的圖片線上路徑
}else{
this.$alert({message: '上傳失敗', btn: false})
}
},
handleAvatarError (res, file) {
this.$alert({message: '選擇圖片失敗', btn: false})
/*this.imageUrl = URL.createObjectURL(file.raw);*/
},
css代碼,修改原組件的樣式
.filesC .avatar-uploader .el-upload {
border: 1px solid #aaa;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.filesC .avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.filesC .avatar-uploader-icon {
font-size: 20px;
color: #8c939d;
width: 141px;
height: 54px;
line-height: 54px;
text-align: center;
background: white;
}
.filesC .avatar {
width: 141px;
height: 54px;
display: block;
}
