vue中element的上传图片功能

1.上传单张图片

<el-form-item label="上传照片" prop="avatar">
    <el-upload 
        class="avatar-uploader" 
        action="" 
        :show-file-list="false" 
        :before-upload="beforeUpload"
    >
        <img v-if="form.avatar" :src="form.avatar" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
</el-form-item>
beforeUpload(file) {
    const isJPG = file.type === "image/jpeg" || file.type == "image/png";
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 或 PNG 格式!");
        return;
    }
    if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return;
    }
    const fileData = new FormData();
    fileData.append("avatar", file);
    //upload为上传的接口
    upload(fileData).then(res => {
        this.imgUrl = res.imgUrl;
        //对返回的图片地址进行回显
        this.$set(this.form, "avatar", this.imgUrl);
    });
}

action表示必选参数,上传的地址,虽然是必传,但有些情况后端不支持这么做,要我们以某种形式传到服务器,那么我们只能在action中传入空字符串。然后在beforeUpload函数中传取数据给服务器,根据服务器返回的地址进行回显。
发现在上传过程中会传两遍,有一遍是传到本地的localhost的,我们需要在beforeUpload最后加上return false来阻止浏览器的默认行为。

2.上传多张图片

<el-form-item label="上传图片" prop="images">
    <el-upload
      action=""
      :limit="3"
      list-type="picture-card"
      :on-exceed="handleExceed"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :file-list="fileList"
    >
      <i class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
</el-form-item>

list-type="picture-card"表示以下面这种方式展示图片
beforeUpload函数同上传单张图片一样的逻辑
filelist这个数组里存放的是上传的图片,它们会依次排放展示,不要自己再v-for循环遍历出来

建议在弹框中完成上传多张图片的逻辑
在这里插入图片描述

//删除
handleRemove(file) {
  this.fileList = this.fileList.filter(item => item.uid !== file.uid);
},
handleExceed() {
  this.msgError("最多只能传3张照片");
}

 ————————————————
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值