首页 > 解决方案 > 嵌套条件语句逻辑错了?

问题描述

我正在尝试对我的文件上传进行一些验证我正在检查 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');
        }
    }

控制台输出:

在此处输入图像描述

标签: javascript

解决方案


这里的第二个测试将始终评估为 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
}

推荐阅读