<template>
<div>
<a-upload
class="upload-btn"
:action="'#'"
:show-upload-list="false"
:customRequest="httpRequest"
:before-upload="beforeUpload"
>
顶部图片
</a-upload>
</div>
</template>
<script>
import { uploadArticleFile } from '@/api/edit'
export default {
components: {},
data () {
return {}
},
mounted () {
},
methods: {
async httpRequest (file) {
const formData = new FormData()
const _this = this
const reader = new FileReader()
reader.readAsDataURL(file.file)
reader.addEventListener('loadend', function (e) {
const image = new Image()
image.src = e.target.result
image.onload = async function () {
if (image.width !== 1920 || image.height !== 268) {
_this.$message.error('需要符合要求尺寸的图片!')
return false
} else {
formData.append('file', file.file)
const { code, data } = await uploadArticleFile(formData)
if (code === 200) {
_this.$message.success('上传成功!')
_this.$emit('uploadImg', data.url)
} else {
_this.$message.error('上传失败!请重新上传')
}
}
}
})
},
// 检查图片格式和图片大小, 限制1920尺寸
async beforeUpload (file) {
// 图片格式限制为 jpeg、png
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
if (!isJpgOrPng) {
this.$message.error('请选择jpg/png图片')
return false
}
// 图片大小限制为 10M以内
const isLt10M = file.size / 1024 / 1024 <= 10
if (!isLt10M) {
this.$message.error('图片大小不能超过10MB,请重新上传')
return false
}
return isJpgOrPng && isLt10M
}
}
}
</script>
<style lang="less" scoped>
.upload-btn {
width: 100%;
height: 76px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #fafafa;
border: 1px dashed #d9d9d9;
border-radius: 2px;
cursor: pointer;
margin-bottom: 10px;
/deep/ .ant-upload {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
}
</style>
a-upload自定义上传图片
最新推荐文章于 2024-09-03 18:25:53 发布
这是一个Vue组件示例,用于实现图片上传功能。组件使用了Ant Design Vue库,支持图片格式和大小验证,并在上传前检查图片尺寸是否符合1920x268的要求。如果图片不符合尺寸,将提示错误;否则,会调用`uploadArticleFile`接口上传文件,并在成功后显示上传成功的消息,同时触发父组件的`uploadImg`事件。
摘要由CSDN通过智能技术生成