天天看點

利用element的上傳到自己伺服器

現實中我們很多的需求是利用element的upload的ui來做上傳功能,但是我們自己寫上傳規則,是以我們把上傳規則寫在before-upload裡面 最後return false這樣element就不會繼續執行上傳邏輯了

  1. 頁面ui部分代碼
    <el-upload
        class="upload-demo"
        accept=".jpg,.jpeg,.png"
        action="https://jsonplaceholder.typicode.com/posts/"
        :show-file-list="false"
        :before-upload="beforeAvatarUpload"
        >
        <img v-if="addform.img_path" :src="this.$baseURL+'/'+addform.img_path" class="avatar">
        <div class="form-upload-defult" v-else>
            <div class="img">編輯</div>
            <div class="text">
                <p>上傳營養品圖檔</p>
                <p>支援上傳jpg、jpeg、png檔案,且不超過800kb</p>
            </div>
        </div>
        
    </el-upload>
               
  2. js部分代碼
    我們利用axios 進行上傳 因為涉及到跨域
    
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 0.8;
    
    //   if (!isJPG) {
    //     this.$message.error('上傳頭像圖檔隻能是 JPG 格式!');
    //   }
      if (!isLt2M) {
        this.$message.error('上傳頭像圖檔大小不能超過 800k!');
        return false;
      }
    
      let formData = new FormData()
      formData.append('file_path', file)
      this.$axios.post(`p/cater/caterUpload`, formData).then(response => {
        if (response.code == 0) {
          this.addform.img_path = response.data;
        } else {
          this.$message({
            message: response.message,
            type: 'error'
          })
        }
      }).catch((error) => {
        console.log(error)
      })
      // return isJPG && isLt2M;
      return false;
    },
               

繼續閱讀