vue el-upload 上傳文件格式校驗方法
vue el-upload 上傳文件格式校驗
<el-upload class="avatar-uploader" action="#" :show-file-list="false" :before-upload="beforeAvatarUpload"> <i class="el-icon-plus avatar-uploader-icon"></i> </el-upload>
1、文件大小驗證
file.size 以字節(jié)Byte為單位(Blob類型),1MB=1024KB,1KB=1024Btye
<script> export default { methods: { beforeAvatarUpload(file) { const isLt2M = file.size / 1024 / 1024 < 2; // 小于2M if ( !isLt2M ) { console.log('文件大小超出2M'); } } } } </script>
2、文件格式驗證
文件名后綴是支持大小寫的,如.mp4 .Mp4 .mP4 .MP4都是可以正常播放的,所以我們校驗的時候通過先將其轉成小寫,再進行校驗。(圖片同理)
file.name.split('.')[1].toLowerCase() != 'mp4'; // 視頻不是.mp4格式的
let formatArr = ['image/png','image/jpg','image/jpeg']; const isPic = ( formatArr.indexOf(file.type.toLowerCase()) != -1 ); // 是否為圖片
3、視頻時長驗證
函數可以直接使用,file為el-upload上傳的file文件;得到的結果單位為秒,保留兩位小數。
// 獲取視頻文件時長 getVideoTime(file){ return new Promise((resolve, reject) => { let url = URL.createObjectURL(file); let audioElement = new Audio(url); audioElement.addEventListener('loadedmetadata',function(_event){ const time = Math.round(audioElement.duration * 100) / 100; // 時長為秒,保留兩位小數 resolve(time); }); audioElement.addEventListener('error', () => resolve(0)); }) },
el-upload上傳文件 需要在請求之前加一個校驗文件內容格式請求
before-upload
data(){ return { ... //判斷是否需要做文件檢查 checkFileFormat:false } }, beforeUpload(rawFile) { this.loading = true; ... 檢查文件格式 檢查文件大小 ... if (this.checkFileFormat) { return new Promise(async (resolve, reject) => { const fd = new FormData() fd.append('file', rawFile) const res = await checkRpAttFile(fd) this.loading = false; if (!res.success) { Message.error(res.message); reject() } else { resolve() } }) } else { return true } },
到此這篇關于vue el-upload 上傳文件格式校驗的文章就介紹到這了,更多相關vue el-upload 上傳文件內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue項目中Element UI組件未注冊的問題原因及解決方法
在 Vue 項目中使用 Element UI 組件庫時,開發(fā)者可能會遇到一些常見問題,例如組件未正確注冊導致的警告或錯誤,本文將詳細探討這些問題的原因、解決方法,以及如何在需要時撤銷相關操作,需要的朋友可以參考下2025-01-01Vue 路由間跳轉和新開窗口的方式(query、params)
這篇文章主要介紹了Vue 路由間跳轉和新開窗口的方式,本文主要通過query方式和params方式介紹,需要的朋友可以參考下2019-12-12vue3使用vis繪制甘特圖制作timeline可拖動時間軸及時間軸中文化(推薦)
這篇文章主要介紹了vue3使用vis繪制甘特圖制作timeline可拖動時間軸,時間軸中文化,本文結合實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-02-02