Vue+elementUI+SpringBoot项目-上传用户头像(1)

前言

  一直感觉头像上传是个非常基础简单的功能,可是实现此功能用了将近2天的时间,所以记录下走过的坑。
  前端采用vue+elementui,后端采用springboot。本篇文章先介绍前端图片的上传,后一篇介绍后端如何进行图片的接收和存储的。

实现

(1)首先用element ui为我们定义的头像上传组件。

    <el-upload
          class="avatar-uploader"
          action="#"
          accept=".jpg,.jpeg,.png,.JPG,.JPEG"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleEditAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="this.editImageUrl" :src="this.editImageUrl" class="add-userface-img">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
  • action字段:表示表单提交的url,这里不直接提交,而是和用户信息一起发送提交请求。
  • auto-upload字段: 关闭自动提交
  • on-change:当修改头像会触发此方法
  • before-upload:在上传前监测图片类型和大小
   handleAvatarSuccess(file) {
      //addImageFile  addImageUrl 自己在data中定义 file指的就是选择的文件对象
      this.addImageFile = file;
      this.addImageUrl = URL.createObjectURL(file.raw);
    },

    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
      }
      return  isLt2M;
    },

使用到的css如下:

.avatar-uploader{
  display: flex;
  justify-content: center;
  margin-bottom: 5px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  align-items: center;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 130px;
  height: 130px;
  line-height: 130px;
  text-align: center;
}
.avatar {
  width: 130px;
  height: 130px;
  display: block;
}

(2)修改用户信息的post请求

 editManage(){
      //因为后端图片是单独用MultipartFile接受,所以用户信息与头像分为两部分进行提交
      var fd = new FormData();
      //这里是用户的数据
      fd.append("manage",JSON.stringify(this.editForm));
      //这里是头像即图片的数据 这里一定要注意 .raw
      fd.append("image",this.editImageFile.raw);
      //axios
      this.putRequest("/manage/",fd).then(resp=>{
        if(resp){
         //更新用户列表
        }
        this.editDialogVisible = false
      })
    },
总结

如上就是前端上传头像的所有代码,如有疑问欢迎评论!

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值