Vue+Springboot实现头像上传

  • Post author:
  • Post category:vue


1、vue引用elementui的头像上传功能:

头像限制为.jpg格式,当选中文件后会自动调用接口,按照官方的文档不发进行文件预览,只能当文件上传成功后才可以返回返回文件进行查阅。

html代码:

<div class="upload">
    <el-upload
    :action=avatarUrl
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload">
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
       </el-upload>
    <span>(图片为jpg格式、且不能超过2M)</span>
</div>

js代码:

handleAvatarSuccess(res, file) {
      this.$message.success("修改头像成功")
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
    }
    return isJPG && isLt2M;
},

css代码:

  .upload{
    width: 30%;
    float: right;
     .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .span{
      margin-top: 5px;
      display: block;
      width: 178px;
      font-size: 10px;
      color: #606266;
      text-align: center;
    }
  }
  .usercode{
    padding-left:20px ;
    margin-bottom:20px ;
  }

Springboot代码:

先判断文件的格式,然后在static下存储该文件,在把文件的地址存在数据库中。

/**
     * 上传照片
     * @param user
     * @param file
     * @return
     */
    @PostMapping("/toUploadUserAvatar")
    public CommonResult updateAvatar(User user, MultipartFile file){
        //判断文件类型
        String pType = file.getContentType();
        pType = pType.substring(pType.indexOf("/")+1);

        if("jpeg".equals(pType)){
            pType="jpg";
        }
        long time=System.currentTimeMillis();

        String path = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\images\\avatar\\"+user.getCode()+"."+pType;

//        System.out.println(path);

        try{
            userService.addVatar("http://localhost:80/avatar/"+user.getCode()+"."+pType,user);
            file.transferTo(new File(path));
            //文件路径保存到数据库中从而读取
            System.out.println(path);
            return CommonResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return CommonResult.failed();
        }
    }



版权声明:本文为weixin_47500620原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。