1、template代碼如下
代碼解析:
action為空就可以;
show-file-list 是否顯示已上傳文件列表
before-upload:綁定的是上傳圖片前要執(zhí)行的方法用來限制圖片的大小、格式
http-request:綁定的是上傳圖片的方法
img 標(biāo)簽里放的是上傳成功后顯示出來的圖片
i 標(biāo)簽里 放的是默認(rèn)未上傳圖片時(shí)的圖標(biāo)
<el-upload
class="avatar-uploader"
action=""
:show-file-list="false"
:http-request="selectPicUpload"
:before-upload="beforeAvatarUpload"
>
<img v-if="iconVal" width="85px" height="85px" :src="iconVal" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
2、js代碼 (兩個(gè)方法)
//上傳圖標(biāo)事件
selectPicUpload(obj) {
let fd = new FormData(); //參數(shù)的格式是formData格式的
fd.append('uploadFile', obj.file); //參數(shù)
this.$api.StoreDiodeUpload(fd).then(res => {
if (res) {
this.iconVal =res;
this.message('上傳成功', 1)
} else {
this.message('上傳失敗', -1)
}
}).catch(error => {
})
},
//對(duì)上傳圖片的大小、格式進(jìn)行限制
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isJPG2 = file.type === 'image/jpg';
const isPNG = file.type === 'image/png';
const isLt5M = file.size / 1024 / 1024 < 5;
if (!isJPG && !isJPG2 && !isPNG) {
this.$message.warning('只支持jpg或png格式圖片');
}
if (!isLt5M) {
this.$message.warning('請(qǐng)上傳5MB以內(nèi)的圖片!');
}
return (isJPG || isJPG2 || isPNG) && isLt5M;
}