近日因業(yè)務(wù)需求,要用到ElementUI的el-upload上傳組件來實現(xiàn)拖拽上傳功能撕予。
結(jié)果鲫惶,發(fā)現(xiàn)在組件上加上accept文件過濾字段之后,如果用戶選錯文件進行拖拽上傳時实抡,上傳事件會直接被終止欠母,而又不會彈出任何錯誤信息——例如,提示上傳的文件格式不對吆寨,這種體驗很不友好赏淌。
通過測試發(fā)現(xiàn),原來加上accept字段之后啄清,如果拖拽的文件格式不對六水,根本不會觸發(fā)before-upload,所以原本用來驗證文件的事件根本沒被調(diào)用辣卒,因此沒有彈出任何提示掷贾。
經(jīng)過總結(jié),發(fā)現(xiàn)只要在el-upload組件加上原生的drop事件即可解決上述問題荣茫。即:
@drop.native="e => beforeUploadHandler(e.dataTransfer.files[0])"
以下為代碼示例:
<template>
<div class="upload-wrap">
<el-upload
action
accept=".png,.jpg,.jpeg"
msgPage
drag
:show-file-list="false"
:http-request="e => requestHandler(e)"
:before-upload="file => beforeUploadHandler(file, 512000, ['image/png', 'image/jpg', 'image/jpeg'])"
//該處加入原生drop事件想帅,獲取拖拽的文件
@drop.native="e => beforeUploadHandler(e.dataTransfer.files[0], 512000, ['image/png', 'image/jpg', 'image/jpeg'])"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">將文件拖到此處,或<em>點擊上傳</em></div>
<div class="el-upload__tip" slot="tip">只能上傳PNG,JPG,JPEG文件啡莉,且不超過500kb港准。</div>
</el-upload>
</div>
</template>
<script>
export default {
name: 'default',
data() {
return {
};
},
methods: {
//http-request: 覆蓋默認的上傳行為,自定義上傳方法
requestHandler(e){
console.log(e);
},
//before-upload: 上傳之前進行文件驗證
beforeUploadHandler(file, size, accept){
console.log(file, size, accept);
//驗證文件大小
if(file.size > size){
this.$message.info(`上傳文件不能大于500kb`);
return false;
}
//驗證文件類型
if(accept.indexOf(file.type) == -1){
this.$message.info(`只能上傳${accept.join('咧欣、')}文件`);
return false;
}
return true;
}
}
};
</script>
<style lang="scss" scoped>
.upload-wrap{
margin-top: 30px;
text-align: center;
}
</style>