Node:
實(shí)現(xiàn)以下一段驗(yàn)證類型的函數(shù),
主要檢驗(yàn):
- 以及此文件是否存在
- 上傳的文件是否為xlsx文件格式
- 文件大小<8M
- 前端中上傳的表單name為 'xlsxfile'的文件
只有當(dāng)條件均符合時(shí)才能通過校驗(yàn)返回True
值。
前提已知
- 使用multer中間件,上傳的 file返回?cái)?shù)據(jù)結(jié)構(gòu)為:
#
const file = {
fieldname: 'xlsxfile',
originalname: 'Y~Z.xlsx',
encoding: '7bit',
mimetype:
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
destination: 'D:\\Code\\upload_TEMP',
filename: 'data.xlsx',
path: 'D:\\Code\\upload_TEMP\\data.xlsx',
size: 9848,
};
一般寫法
- 憋一口氣的寫法:
import {existsSync} from 'fs';
const validate =(file)=>{
const xlsxMIME =
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
if(existsSync(file)&&file.mimetype===xlsxMIME&&file.size<=8*1024*1024&&file.fieldname!=='xlsxfile'){
return true;
}
return false;
}
- n連發(fā)if判斷寫法:
import {existsSync} from 'fs';
const validate =(file)=>{
const xlsxMIME =
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
if(!existsSync(file)){
return false;
}
if(file.mimetype!==xlsxMIME){
return false;
}
if(file.size>=8*1024*1024){
return false;
}
if(file.fieldname!=='xlsxfile'){
return false;
}
return true;
}
優(yōu)雅的寫法
使用 R.allPass 方法
import { existsSync } from 'fs';
const validate = (file) => {
const xlsxMIME =
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
const validRules = [
(file) => existsSync(file.path),
(file) => file.mimetype === xlsxMIME,
(file) => file.size<=8*1024*1024,
(file) => file.fieldname === 'xlsxfile'
];
return R.allPass(validRules)(file);
};