vue3项目上传裁剪后的头像

需求

项目中需要上传头像,但是头像的大小是有规定的,所以要经过裁剪过后符合要求才进行上传,去搜索看了很多封装的裁剪组件,最后选择了VueCropper这个组件。

一、下载VueCropper

在node环境下,npm install vue-cropper@next 命令下载组件
使用页面引入如下语句:

import { VueCropper } from "vue-cropper";
import "vue-cropper/dist/index.css";
import axios from "axios";

二、VueCropper使用

我这里是使用弹框,组件功能写在弹框内。

<el-dialog
      v-model="signatureVisible"
      title="上传头像"
      width="40%"
      :close-on-click-modal="false"
    >
      <div style="height: 500px">
        <div style="font-size: 15px; margin-bottom: 10px">
          提示:请上传正面清晰的免冠照片,建议尺寸为200×200像素,若照片不符合200x200像素的,请将人像拖拽到蓝色边框线围住的区域内进行上传。
        </div>
        <div style="margin-bottom: 10px">
          <el-button type="primary" @click="clickAvatar"
            >点击上传头像</el-button
          >
          <input
            type="file"
            accept="image/*"
            id="jsFileInput"
            @change="handleFileChange"
            style="display: none"
          />
        </div>
        <div style="width: 100%; height: 70%" class="flexCenter">
          <VueCropper
            ref="cropperRef"
            :img="imageUrl"
            :autoCrop="true"
            :fixedBox="true"
            :outputType="'jpeg'"
            :autoCropWidth="200"
            :autoCropHeight="200"
          />
        </div>
        <div class="flexCenter" style="margin-top: 20px">
          <el-button
            style="width: 80px; margin-right: 15px"
            @click="signatureVisible = false"
            >取消</el-button
          >
          <el-button type="primary" @click="cropAndUpload" style="width: 80px"
            >确定上传</el-button
          >
        </div>
      </div>
    </el-dialog>

//js代码
const imageUrl = ref(""); // 图片地址
const handleFileChange = (e) => {
  const file = e.target.files[0];
  if (!file) return;
  const reader = new FileReader();
  reader.onload = (event) => {
    imageUrl.value = event.target.result;
  };
  reader.readAsDataURL(file);
};

const clickAvatar = () => {
  const avatar = document.getElementById("jsFileInput");
  avatar.click(); //原生input文件上传,默认文字去掉,触发文件上传事件
};

const cropAndUpload = async () => {
  const cropper = cropperRef.value;
  cropper.getCropBlob(async (blob) => {
    const formData = new FormData();
    const file = new File([blob], "avatar.jpg", { type: "image/jpeg" });
    formData.append("file", file);
    try {
      axios.post('api', formData).then((res) => {
        const data = res.data;
        if (res.status == 200) {
          ruleForm.value.imageFile = data.object.id;
        }
      });
    } catch (error) {
      console.error("上传失败", error);
    }
  });
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值