需求
项目中需要上传头像,但是头像的大小是有规定的,所以要经过裁剪过后符合要求才进行上传,去搜索看了很多封装的裁剪组件,最后选择了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);
}
});
};
3532

被折叠的 条评论
为什么被折叠?



