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