<template>
<div>
<el-upload ref="uploadFile"
:headers="headers"
accept='*'
action='123'
:http-request='httpRequest'
:file-list="fileList"
:show-file-list="true"
:before-upload="beforeUpload"
:on-error='uploadError'
:on-success='handleSuccess'
:on-remove="fileRemove">
<el-button size="small"
type="primary">{{title}}</el-button>
</el-upload>
</div>
</template>
<script>
import { uploadFile } from "@/api/pc/audit.js"
export default {
props: {
title: {
type: String,
default: '点击上传附件'
},
uploadFileUrl: {
type: String,
default: ‘http//:www.com’// 上传的图片服务器地址,
}
},
data () {
return {
fileList: [],
headers: {
Authorization: "Bearer " + 123,
tokenid: 123
},
}
},
methods: {
handleSuccess (res) {
if (res.errorCode) { // 有错误码
//抛出异常信息
}
},
uploadError (error) {
},
beforeUpload (file) {
},
// 删除临时文件
fileRemove (file) {
this.clearFileList(file.uid)
},
httpRequest (fileObj) {
console.log("fileObj", fileObj)
let file = fileObj.file
//禁止上传重复名字的文件
let valid = this.fileList.find(el => el.name === file.name)
if (valid && valid.uid) {
this.$modal.msgError('请勿上传相同名字的文件');
let uid = file.uid;
this.clearShowList(uid)
return
}
const formData = new FormData();
formData.append("file", file);
uploadFile(formData).then(res => {
this.fileList.push({ name: file.name, uid: file.uid, url: res.result.url });
console.log("this.fileList", this.fileList)
}).catch(error => {
console.log("上传失败", error)
//上传失败不显示列表文件
let uid = file.uid;
this.clearShowList(uid)
this.clearFileList(uid)
})
},
//下面两个方法是重点
//清空文件列表
clearFileList (uid) {
let fileListIdx = this.fileList.findIndex(item => item.uid === uid)
this.fileList.splice(fileListIdx, 1)
},
//清空显示列表
clearShowList (uid) {
let idx = this.$refs['uploadFile'].uploadFiles.findIndex(item => item.uid === uid)
this.$refs.uploadFile.uploadFiles.splice(idx, 1)
}
}
}
</script>
<style>
</style>
el-upload调用接口上传失败依然回显问题解决
最新推荐文章于 2024-06-03 22:36:51 发布