javascript - 嵌套条件语句逻辑错了?
问题描述
我正在尝试对我的文件上传进行一些验证我正在检查 3 件事
1) 文件提交了吗?2) 文件类型是否正确?3) 文件大小小于允许的数量
出于某种奇怪的原因,我的嵌套条件语句没有返回我期望的结果。
我希望它像:
如果用户输入文件,请检查文件类型。如果文件类型通过,检查文件大小,如果文件大小通过,则将文件提交给服务器。
当我在控制台中测试它时,如果我不提交文件,则第一个 if 块通过但第二个在我同时提交正确的文件类型和错误的文件类型时失败。此外,我检查了文件大小块,这两种情况都失败了。
这是我的代码和控制台上的输出。对于文件类型,我已经设置了真实文件类型的状态,以防用户试图欺骗文件。
async onSubmit(e){
e.preventDefault();
console.log(this.state);
// file size bytes in mb
var fileCheck = Math.floor(Math.log(this.state.fileSize) / Math.log(1024));
console.log(fileCheck);
//Check if a uploaded photo was taken.
if(this.state.fileObject === ''){
console.log('no file was submitted');
} else if(this.state.fileType !== 'image/jpeg' || this.state.fileType !== 'image/jpg' || this.state.fileType != 'image/png'){
// check file type
console.log('wrong file type');
} else if(fileCheck >= 2){
// check file size
console.log('file is too big');
}
else {
console.log('passed all file checks');
}
}
控制台输出:
解决方案
这里的第二个测试将始终评估为 true:
else if(this.state.fileType !== 'image/jpeg' || this.state.fileType !== 'image/jpg' || this.state.fileType != 'image/png'){
我建议改为检查数组:
const allowedFileTypes = ['image/jpeg', 'image/jpg', 'image/png'];
// ...
else if (!allowedFileTypes.includes(this.state.fileType)) {
// err, condition failed
}
.includes
是一种半新的方法,如果您支持古老的浏览器并且不使用 polyfill,请indexOf
改为测试:
const allowedFileTypes = ['image/jpeg', 'image/jpg', 'image/png'];
// ...
else if (allowedFileTypes.indexOf(this.state.fileType) === -1) {
// err, condition failed
}
推荐阅读
- jsf - 如何在对话框顶部显示日历?
- mongodb - 如何有效地获取mongodb记录中相关键的列表
- http - Youtube 的 PCAP 分析
- javascript - 如何从 react-chartjs-2 的画布中删除一条垂直线?
- typescript - 从 TypeScript 中的类获取自身属性的接口
- .net - Visual Studio 2019 的 nuget 数据包管理器中未显示实体框架
- neo4j - Neo4j 4.3 集群创建总是失败
- django - Django表单数据未保存到数据库
- variables - 无法从 Liquid 中的模板访问 Snippet 中定义的变量
- google-cloud-platform - Google Cloud Storage 的访问日志有多完整?