利用element的上传到自己服务器

34 篇文章 0 订阅
13 篇文章 0 订阅

现实中我们很多的需求是利用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;
    },

     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值