vue+element-ui 的el-upload 實(shí)現(xiàn)圖片上傳

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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容