el-upload upload avatar vue3 js project

① HTML

          <el-tooltip content="点击更换头像" placement="top">
            <el-upload
              class="avatar_uploader"
               :action="uploadImgUrl"
               :data="ImageData"
              :show-file-list="false" 
              :headers="headers"
               method="put"
               :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img  :src="userStore.avatar" />
            </el-upload>
          </el-tooltip>

Attribute interpretation:

action   -- the complete API corresponding to the request to the backend, including the test address

For example http://192.168.1.0:8080/api/uploadHeadImage 

http://192.168.1.0:8080 It is best to use a global variable instead of the test address to prevent frequent changes later

data -- the data file carried when uploading, here is the avatar photo , written in the before-upload event

show-file-list --Whether to display the list of uploaded files. The default is true. It will be used in uploading multiple files. Here is an avatar (single), so set it to false

header -- The data in the request header can generally be seen with a token

methods -- upload method or see the interface document is generally put

on-success -- the callback event after the upload is successful

before-upload -- the callback event before uploading, add the data required by the interface document here

② JS

<script setup>

//状态管理里面获取用户头像信息
import useUserStore  from '@/store/modules/user';
const userStore = useUserStore();

// headers
const headers = ref({ "token":  getToken() });

// 头像上传接口
const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + "/api/setAvatar")
// 上传参数
const ImageData = ref()


// 上传之前
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/jpeg"&&rawFile.type !== "image/png"&&rawFile.type !== "image/jpg") {
    ElMessage({
      showClose:true,
      message:'图片只能是JPG或PNG格式!',
      type:'warning'
    });
    return;
  }
  if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage({
      showClose:true,
      message:'图片大小不能超过5MB!',
      type:'warning'
    });
    return;
  }
// 一般是formData格式
  ImageData.value = new FormData();
// 'file'具体是什么字段看项目接口文档
  ImageData.value.append('file',rawFile);
};

// 上传成功回调
const handleAvatarSuccess = (res, uploadFile) => {
 userStore.avatar = URL.createObjectURL(uploadFile.raw);
};


</script>

The CSS part does not need to show that the size of the image and the size of the container are set to be the same.

Effect:

Guess you like

Origin blog.csdn.net/ICUiseeyou/article/details/130066213