1、html结构
<el-upload
:action="uploadPicAction"
:headers="{'token': token }"
:before-upload="beforeExcelUpload"
:on-success="onUploadSuccessPicture"
:on-remove="handleRemovePic"
:on-exceed="handleExceed"
list-type="picture-card"
:file-list="picList"
:limit="9"
multiple
accept=".jpg,.png,.gif,.jpeg,.psd"
>
<i class="el-icon-plus" />
</el-upload>
2、js代码
methods: {
beforeExcelUpload(file) {
let fileReg = ''
let errMsg = ''
const picReg = /\.(jpg|png|gif|jpeg|psd)$/
const attachmentReg = /\.(doc|docx|ppt|pptx|xls|xlsx)$/
const picErrorMsg = '只能上传图片格式,如:|.jpg |.png |.gif |.jpeg |.psd格式!'
const attachmentErrorMsg = '只能上传文档格式格式,如:|.doc |.docx |.ppt |.xls |.xlsx格式!'
fileReg = this.uploadType === 1 ? attachmentReg : picReg
errMsg = this.uploadType === 1 ? attachmentErrorMsg : picErrorMsg
let limitMax = 0
const limitErrMsg = this.uploadType === 1 ? '200M' : '400KB'
const limitMin = (file.size / 1024 / 1024) > 0
const limitFileMax = (file.size / 1024 / 1024) < 200
const limitPictureMax = (file.size / 1024 / 1024) < (400 / 1024)
limitMax = this.uploadType === 1 ? limitFileMax : limitPictureMax
if (!fileReg.test(file.name)) {
this.$message.error(errMsg)
}
if (!limitMin) {
this.$message.error('上传的文件不能为空!')
} else if (!limitMax) {
this.$message.error(`上传的文件大小不能超过 ${limitErrMsg}!`)
}
return fileReg.test(file.name) && limitMin && limitMax
},
onUploadSuccessAttachments(res) {
console.log('上传成功', res, this.fileList)
if (res.status === 200) {
this.ruleForm.attachList.push({
filename: res.data.filename,
path: res.data.path
})
}
},
onUploadSuccessPicture(res, file, fileList) {
if (res.status === 200) {
this.ruleForm.pictureList.push({
filename: res.data.name,
path: res.data.path
})
}
},
handleRemovePic(file, fileList) {
if (file && file.status === 'success') {
const index = this.ruleForm.pictureList.findIndex(item => item.filename === file.name)
this.ruleForm.pictureList.splice(index, 1)
}
},
handleExceed(files, fileList) {
let msg = ''
msg = this.uploadType === 1 ? '最多只能上传9个文件!' : '最多只能上传9张图片!'
this.$message.warning(msg)
}
}