为什么我所有的文件上传都跳过 else if 条件?

问题描述 投票:-1回答:1

我有一个检查文件类型的函数,这次我想检查文件是否正确,文件大小是否足够。 这次,我想检查文件是否正确,文件大小是否足够。 如果文件扩展名是正确的,但文件大小大于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;
}
javascript debugging
1个回答
1
投票

其实,它确实进入了 "else if "块,只是检查了 此处.确保你的环境支持 文件Api最简单的方法是检查全局对象是否存在FileReader。

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

0
投票

file.value 出于安全考虑,通常是行不通的。使用新的 fileinput.files

要检查瓷砖类型。

let file = realFileBtn.files[0];
let type = file.type; //returns the MIME Type

//Method 1
if(/(\.jpg|\.jpeg|\.png|\.bmp|\.mov|\.MOV)$/i.test(file.type)) {
  //code here
}

//Method 2
let type2=file.type.split('/')[0];
if(type2=="video" || type2=="image") {
  //code here
}

要检查文件的大小。

if(file.size<maxSize) {
  //code here
}

在MDN上查看更多

© www.soinside.com 2019 - 2024. All rights reserved.