element-ui中上傳圖片組件的使用

<el-upload
   class="avatar-uploader"
    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>

 beforeAvatarUpload(file) { //上傳前的函數
//上傳前對圖片類型和大小進行判斷
   const isJPG = file.type === 'image/jpeg';
   const isLt2M = file.size / 1024 / 1024 < 2;

   if (!isJPG) {
     this.$message.error('上傳頭像圖片只能是 JPG 格式!');
   }
   if (!isLt2M) {
     this.$message.error('上傳頭像圖片大小不能超過 2MB!');
   }
   //校驗成功上傳文件
   if(isJPG && isLt2M == true){
     console.log(file);

     //將文件轉化爲formdata數據上傳
     let fd = new FormData()
     fd.append('files', file)
     console.log(fd)
  
   // post上傳圖片

      let that = this
    
       new Promise(function (resolve, reject) {
           axios.post('圖片上傳的路徑', fd, 
                 {
                 headers: {
                 'Content-Type': 'multipart/form-data'
                 }
               }).then((response) => {
                  that.imgId = response.data.data
                   resolve(that.imgId);
               }).catch((error) =>{
                   this.$message.error('頭像上傳失敗,請重新上傳!');
               })
              }).then(function (id){
                  console.log(id)
           //    that.axios.get('/file/view/'+id)
           //     .then((response) => {
           //          that.imageUrl = response.request.responseURL;
           //      })
         })         
       }
             return isJPG && isLt2M;

 },
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章