<el-form-item label="头像">
<div>
<el-image class="avatar" :src="form.headImg" :preview-src-list="[form.headImg]"></el-image>
</div>
<el-upload ref="upload" :action="UploadHttp" class="avatar-uploader" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
</el-upload>
</el-form-item>
import type { UploadProps } from 'element-plus'
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
const fileSize = rawFile.size;
if (fileSize / 1024 / 1024 > 2) {
ElMessage.error('头像图片大小不能超过 2MB!');
return false
}
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsArrayBuffer(rawFile);
reader.onload = async (e) => {
try {
const content = new Uint8Array(e.target.result);
const hash = CryptoJS.SHA256(CryptoJS.lib.WordArray.create(content)).toString();
const { data } = await axios.get(`${api.http}/api/Uploader/FileExists?fileSize=${fileSize}&sha256Hash=${hash}`);
if (data.data.isExists) {
if(form.headImg !== data.data.url){
form.headImg = data.data.url;
}
resolve(false);
} else {
resolve(true);
}
} catch (error) {
reject(false);
}
};
reader.onerror = (error) => {
reject(false);
};
});
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
response,
uploadFile
) => {
console.log(uploadFile);
form.headImg = URL.createObjectURL(uploadFile.raw!)
}