Element 元件 el-upload 獲取上傳失敗時的返回資訊
阿新 • • 發佈:2021-04-26
在處理 el-upload 上傳元件在上傳失敗時可以使用 on-error鉤子函式來顯示後端返回的錯誤資訊
//html 區域
<el-upload class="upload-demo" ref="upload" :headers="headers" :action="excelUploadApi"
:on-change="handleChange" :on-error="handleError" :show-file-list="false">
<el-button slot="trigger" class="filter-item" type="warning" size="small"
icon="el-icon-upload">
匯入按鈕
</el-button>
</el-upload>
//利用 :on-error="handleError" 鉤子函式
但在打印出返回的err 發現返回的格式不是能簡單獲取的。我在網上搜索到兩種大神的解決方案,在此記錄下,以便以後遇到~
方案一
參考連結 https://blog.csdn.net/weixin_44839274/article/details/113702000
直接通過 JSON.parse() 去轉換 err.message 而不是轉換 err
handleError(err, file, fileList) { //上傳失敗鉤子函式
console.log('err', err)
console.log('err', JSON.parse(err.message))
if (file.status == 'fail') {
this.$message.error(JSON.parse(err.message) .message)
}
},
方案二
參考連結 https://www.jianshu.com/p/a4f7e97436f4
把錯誤資訊轉成字串,然後去掉" Error: " ,剩下的內容就是個json,然後再轉成物件
handleError(err, file, fileList) { //上傳失敗鉤子函式
console.log('err', err)
let myError=err.toString();//轉字串
myError=myError.replace("Error: ","") // 去掉前面的" Error: "
myError=JSON.parse(myError);//轉物件
console.log(myError);
},