HTML:
<el-upload class="upload-demo" action="https://www.baidu.com" // url :headers="headers" // 请求头,一般填token、orgid等身份校验信息 :with-credentials="true" // 自动获取cookie :data="uploadDataReq" // url中带的参数 :before-upload="checkFileExist" // 上传文件之前触发的事件,一般为调另一个接口检查文件是否存在 :on-success="uploadSuccess" // 上传成功触发的事件,一般为弹窗提示上传成功 :on-remove="removeTechnicalDoc" // 删除文件,可以调删除文件的接口 :on-change="handleChange" // 组件中文件变化事件,可以拿到已经上传的文件列表自定义显示样式 :file-list="fileList"> // 文件列表数组 <el-button size="small" type="primary">点击上传</el-button> </el-upload>
JS:
async checkFileExist (file, fileList) { // 此处一定要用async await把异步请求转为同步,否则文件查重接口还未返回,文件就已经上传了 // console.log(file, fileList) let name = file.name // let arr = name.split('.') let type = this.type // 上传文件入参 this.uploadDataReq.type = type // 检查文件是否存在入参 this.checkExistDataReq[0].type = type this.checkExistDataReq[0].fileName = name await checkFileExist(this.checkExistDataReq).then((response) => { if (response[0].exist) { let result = confirm('该文件已存在,是否覆盖?') // 此处必须用confirm,因为它有回调 console.log(result) if (result) { // 如果用户选择覆盖文件,组件会自动上传文件 } else { throw new Error('1') // 此处必须抛出一个错误,只有throw error可以终止上传文件 } } }) },
如果不喜欢el-upload自带的样式,可以用fileList自己写一个显示文件的div