首页 > 解决方案 > 为什么我所有的文件上传都跳过了 else if 条件?

问题描述

我有一个检查文件类型的功能。这一次,我想检查正确的文件和足够的文件大小。如果文件扩展名正确但文件大小大于 10MB,那么它应该抛出alert();内部else if()条件块。相反,它被跳过了。

我正在使用 37.3MB 的 .mov 文件对其进行测试

我究竟做错了什么?

function fileValidationWinnerPhoto() {
    const realFileBtn = document.getElementById("real-file");
    let filePath = realFileBtn.value;
    let maxSize = 10485760;

    // Allowing file type
    let allowedExtensions = /(\.jpg|\.jpeg|\.png|\.bmp|\.mov|\.MOV)$/i;

    if (!allowedExtensions.exec(filePath)) {
        alert('Invalid file type');
        realFileBtn.value = '';
        return false;
    } else if(allowedExtensions.exec(filePath) && realFileBtn.files[0].size > maxSize) {
        alert("You have the correct file type but your uploaded file is too large!  Try uploading a file that's less than 10MB!");
        return false;
    } else {
        console.log("file accepted");
        fileAcceptedFlag = true;
    }
    return filePath;
}

标签: javascriptdebugging

解决方案


实际上,它确实进入了“else if”块,只是在这里检查。确保您的环境支持File Api 最简单的方法是检查全局对象是否存在 FileReader:

if (window.FileReader) {
 console.log('File API works');
}

推荐阅读