普通校驗上傳文件
export function validUploadFile(type = 'img', file) {
if (!file) {
file = type;
type = 'img'
}
const fileName = file.name;
const m = fileName.match(/\.(\w+)(#|\?|$)/);
const fileType = (m && m[1]).toString().toLowerCase();
const allowHook = {
video: ['mp4', 'ogv', 'ogg', 'webm'],
audio: ['wav', 'mp3', 'ogg', 'acc', 'webm', 'amr'],
file: ['doc', 'docx', 'xlsx', 'xls', 'pdf'],
excel: ['xlsx', 'xls'],
img: ['jpg', 'jpeg', 'png', 'gif']
}
const validType = (allowHook[type] || []).includes(fileType);
if (!validType) {
const supprtTypes = allowHook[type].join(',');
return `只支持${supprtTypes}類型文件上傳`;
}
if (fileName.indexOf('%') > -1 || fileName.indexOf('&') > -1) {
return '上傳文件名稱不能帶有字符"%","&"';
}
const isLt10M = file.size / 1024 / 1024 < 10;
if (type === file && !isLt10M) {
this.$message.error('上傳資料大小不能超過 10MB!');
return false;
}
return '';
}
el-upload + accept限制上傳的文件格式
<el-upload
:accept="this.acceptFile('video')"
:data="{savePath:'technology'}"
:disabled="disabled"
:multiple="isNewAdd"
action="url"
:rowIdex="rowIndex"
:before-upload="handleBeforeUpload.bind(null, 'file')"
:on-success="handleUploadSuccess.bind(null, rowIndex)"
:on-remove="handleUploadRemove.bind(null, rowIndex)"
:on-preview="handlePreview.bind(null, 'file')"
:file-list="selectRow.fileList"
:headers="{ Authorization: token }"
>
<el-button :disabled="disabled" type="primary">點擊上傳</el-button>
</el-upload>
export function acceptFile(e) {
const allowHook = {
video: '.mp4, .ogv, .ogg, .webm',
audio: '.wav, .mp3, .ogg, .acc, .webm, .amr',
file: 'doc,.docx,.xlsx,.xls,.pdf',
excel: 'xlsx,.xls',
img: '.jpg, .jpeg, .png, .gif'
}
if (e) {
return allowHook[e];
}
let srt = null
for (const k in allowHook) {
srt += allowHook[k]
}
return srt
}