el-upload上傳圖片不使用action屬性


<el-upload
action="#"
ref="upload"
list-type="picture-card" //照片牆的樣式
:on-change="handleChange"
:http-request="httpRequest" :before-upload="beforeAvatarUpload"> <i class="el-icon-plus"></i> </el-upload>

注:不使用action屬性就設置為#,然后自定義上傳http-request,element文檔里有。action屬性不能去掉

根據個人需求,我這里只要一張,每次選擇就會把前一張刪除
handleChange(file, fileList) {
   if (fileList.length > 1) {
       fileList.shift()
   }
},

   這里也可以對上傳的圖片做一些限制

 

beforeAvatarUpload(file) {
   const isImg = file.size / 1024 / 1024 < 2
   if (!isImg) {
      this.$message.error('上傳頭像圖片大小不能超過 2MB!')
   }
    
   const isType = file.type === "image/png"
   const isType2 = file.type === "image/jpeg"

   if (!isType && !isType2) {
     this.$message.error('上傳頭像圖片格式為png或jpg')
   }
   return (isType || isType2) && isImg
},

 

  然后就是自定義的上傳方法

httpRequest(data) {
  let _this = this  // 這里要轉一下是因為在下面的function里 this的指向發生了變化
  let rd = new FileReader()
  let file = data.file
  rd.readAsDataURL(file)
  rd.onloadend = function(e) {
     _this.addData.icon = this.result
  }
},
(_this.addData.icon 是新增的時候圖片的參數字段,this.result就是選中的圖片轉成的base64

  最后清空el-upload

this.$refs.upload.clearFiles();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM