uploadFileComp组件
<template>
<div>
<a-spin :spinning="spinning">
<div v-if="fileInfo.fileName">
{{ fileInfo.fileName }}
<a-icon type="delete" style="color:#ff7875" @click="del" />
</div>
<a-upload v-else name="file" :customRequest="customRequest" :beforeUpload="beforeUpload">
<a-button> <a-icon type="upload" /> Upload </a-button>
</a-upload>
</a-spin>
</div>
</template>
<script>
import { upload } from '@/api/upload'
export default {
props: {
fileInfo: {
type: Object,
default: () => {}
}
},
data() {
return {
spinning: false
}
},
methods: {
del() {
let _this = this
this.$confirm({
title: '确认删除?',
onOk() {
_this.$emit('update', { fileName: '', url: '' })
}
})
},
beforeUpload(file) {
return new Promise((resolve, reject) => {
const isLt20M = file.size / 1024 / 1024 < 20
const suffix = file.name.substring(file.name.lastIndexOf('.') + 1).toUpperCase()
const suffixArr = ['PDF']
if (!isLt20M) {
this.$message.error('上传图片大小不能超过 20M!')
return reject(new Error(false))
}
if (!suffixArr.includes(suffix)) {
this.$message.error('上传的文件不符合规范')
return reject(new Error(false))
}
return resolve()
})
},
customRequest(options) {
this.spinning = true
const formData = new FormData()
formData.append('file', options.file)
upload(formData)
.then(res => {
if (res.code === 0) {
this.$emit('update', res.data)
options.onSuccess(res, options.file)
} else {
this.$message.error({
content: res.msg
})
}
})
.catch(err => {
this.$message.error(err)
})
.finally(() => {
this.spinning = false
})
}
}
}
</script>
页面使用
import uploadFileComp from '@/components/uploadFileComp'
<uploadFileComp :fileInfo="fileInfo" @update="updateFnc"></uploadFileComp>