多文件手动上传组件,限制最大文件数量/格式/大小
<template>
<el-upload
class="upload-demo"
ref="uploadRef"
action="#"
:auto-upload="false"
:on-change="handleChange"
:before-upload="beforeUpload"
:accept="accept"
:http-request="handleUpload"
:file-list="fileList">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<div slot="tip" class="el-upload__tip">单个文件最大上传{{ limitMax.singleMax }}MB,全部文件最大上传{{ limitMax.allMax }}MB</div>
</el-upload>
</template>
<script>
import axios from 'axios'
export default {
name: 'uploadFile',
props: {
loadingBtn: { // 按钮loading
type: Boolean,
default: false
},
accept: { // 接受的文件类型
type: String,
default: '.doc, .docx, .xls, .xlsx, .txt, .pdf'
},
limitMax: { // 文件大小限制
type: Object,
default: ()=>{
return {
singleMax: 5,
allMax: 20
}
}
},
limit: { // 文件数量限制
type: Number,
default: 4
},
fileParams: { // 接口其他参数
type: String,
default: 'upup'
}
},
data() {
return {
dialogVisible: false,
fileList: [],
files: [],
time: null
}
},
methods:{
handleUpload() {
let formData = new FormData()
this.files.map(item => {
formData.append('file', item)
})
formData.append('fileParams', this.fileParams)
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
axios.post('接口名', formData, config).then(res=>{
this.$emit('fileData', res.data)
}).catch(e =>{
this.$message({
type: 'error',
message: '上传失败!'
})
console.log('err', e)
}).finally(()=>{
this.$emit('upload:loadingBtn', false)
})
},
// 手动上传
submitUpload() {
if(this.files.length > 0) {
clearTimeout(this.time)
this.time = setTimeout(()=>{
this.time = null
this.handleUpload()
})
} else {
this.$message({
type: 'warning',
message: '请先上传附件!'
})
}
},
// 文件改变
handleChange(file, fileList) {
if(file.status === 'ready') {
if(fileList.length > 4) {
fileList.splice(0,1)
}
let files = []
fileList.forEach(item => {
files.push(item.raw)
})
this.files = files
}
},
// 上传前验证
beforeUpload(file) {
const filename = file.name
const type = filename.substring(filename.lastIndexOf('.'))
const isType = this.accept.includes(type)
const isLtM = file.size / 1024 / 1024 < this.limitMax.singleMax
if(!isType) {
this.$message({
type: 'warning',
message: '文件类型仅支持' + this.accept
})
}
if(!isLtM) {
this.$message({
type: 'warning',
message: '文件大小不能超过' + this.limitMax.singleMax + 'MB'
})
}
}
}
}
</script>
<style lang="scss" scoped>
</style>