2021-09-17 00:18:50 +08:00
|
|
|
<template>
|
|
|
|
<el-upload
|
|
|
|
class="avatar-uploader"
|
|
|
|
action="https://jsonplaceholder.typicode.com/posts/"
|
|
|
|
:show-file-list="false"
|
|
|
|
:on-success="handleAvatarSuccess"
|
|
|
|
:before-upload="beforeAvatarUpload"
|
|
|
|
>
|
|
|
|
<img v-if="imageUrl" :src="imageUrl" class="avatar" />
|
2022-03-10 23:52:13 +08:00
|
|
|
<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
|
2021-09-17 00:18:50 +08:00
|
|
|
</el-upload>
|
|
|
|
</template>
|
|
|
|
|
2021-12-21 15:51:33 +08:00
|
|
|
<script lang="ts" setup>
|
|
|
|
import { ref } from 'vue'
|
|
|
|
import { ElMessage } from 'element-plus'
|
2021-12-04 11:20:06 +08:00
|
|
|
import { Plus } from '@element-plus/icons-vue'
|
2022-03-10 23:52:13 +08:00
|
|
|
|
2022-03-23 18:50:36 +08:00
|
|
|
import type { UploadProps } from 'element-plus'
|
2021-09-17 00:18:50 +08:00
|
|
|
|
2021-12-21 15:51:33 +08:00
|
|
|
const imageUrl = ref('')
|
2022-03-23 18:50:36 +08:00
|
|
|
|
|
|
|
const handleAvatarSuccess: UploadProps['onSuccess'] = (
|
|
|
|
response,
|
|
|
|
uploadFile
|
|
|
|
) => {
|
|
|
|
imageUrl.value = URL.createObjectURL(uploadFile.raw!)
|
2021-12-21 15:51:33 +08:00
|
|
|
}
|
|
|
|
|
2022-03-23 18:50:36 +08:00
|
|
|
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
|
|
|
|
if (rawFile.type !== 'image/jpeg') {
|
2021-12-21 15:51:33 +08:00
|
|
|
ElMessage.error('Avatar picture must be JPG format!')
|
2022-03-23 18:50:36 +08:00
|
|
|
return false
|
|
|
|
} else if (rawFile.size / 1024 / 1024 > 2) {
|
2021-12-21 15:51:33 +08:00
|
|
|
ElMessage.error('Avatar picture size can not exceed 2MB!')
|
2022-03-23 18:50:36 +08:00
|
|
|
return false
|
2021-12-21 15:51:33 +08:00
|
|
|
}
|
2022-03-23 18:50:36 +08:00
|
|
|
return true
|
2021-09-17 00:18:50 +08:00
|
|
|
}
|
|
|
|
</script>
|
2021-09-17 15:27:31 +08:00
|
|
|
|
2022-03-23 18:50:36 +08:00
|
|
|
<style scoped>
|
|
|
|
.avatar-uploader .avatar {
|
|
|
|
width: 178px;
|
|
|
|
height: 178px;
|
|
|
|
display: block;
|
|
|
|
}
|
|
|
|
</style>
|
|
|
|
|
2021-09-17 15:27:31 +08:00
|
|
|
<style>
|
|
|
|
.avatar-uploader .el-upload {
|
2022-04-13 14:40:01 +08:00
|
|
|
border: 1px dashed var(--el-border-color);
|
2021-09-17 15:27:31 +08:00
|
|
|
border-radius: 6px;
|
|
|
|
cursor: pointer;
|
|
|
|
position: relative;
|
|
|
|
overflow: hidden;
|
2022-03-10 23:52:13 +08:00
|
|
|
transition: var(--el-transition-duration-fast);
|
2021-09-17 15:27:31 +08:00
|
|
|
}
|
2022-03-23 18:50:36 +08:00
|
|
|
|
2021-09-17 15:27:31 +08:00
|
|
|
.avatar-uploader .el-upload:hover {
|
2022-03-10 23:52:13 +08:00
|
|
|
border-color: var(--el-color-primary);
|
2021-09-17 15:27:31 +08:00
|
|
|
}
|
2022-03-23 18:50:36 +08:00
|
|
|
|
2022-01-31 23:43:56 +08:00
|
|
|
.el-icon.avatar-uploader-icon {
|
2021-09-17 15:27:31 +08:00
|
|
|
font-size: 28px;
|
|
|
|
color: #8c939d;
|
|
|
|
width: 178px;
|
|
|
|
height: 178px;
|
|
|
|
text-align: center;
|
|
|
|
}
|
|
|
|
</style>
|