2017-08-02 74 views
2

我想允许用户上传仅pdf文件有两种输入文件:超过一个上传检查的文件扩展名复选框

<form onsubmit='return checkExt()' action='upload.php' method='POST'> 
    <label>upload the first file</label> 
    <input type='file' name='fileToUpload' id='fileToUpload' required> 

    <label>upload the secondfile</label> 
    <input type='file' name='fileToUpload1' id='fileToUpload1' required> 
</form> 

我用下面的脚本来检查的扩展名的文件,TO-上传:

<script> 
    function checkExt() { 
     var allowedFiles = [".pdf"]; 
     var form_valid = document.getElementById("fileToUpload"); 
     var form_valid2 = document.getElementById("fileToUpload1"); 
     var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$"); 

     if (!regex.test((form_valid.value.toLowerCase()) &&(form_valid2.value.toLowerCase()))) { 
      alert('only PDF files are allowed'); 
      return false; 
     } 
     return true; 
    } 
</script> 

问题是:当我测试它时,它只检查第一个文件,如果它是pdf或不。它不检查第二个文件。

+0

请参阅https://stackoverflow.com/questions/4234589/validation-of-file-extension-before-uploading-file –

回答

0

在你的第二个检查,如果条件应该反映的第一个,这就是为什么它不工作的原因。 无论如何,最简单和可扩展的方法是遍历“文件”类型的输入字段。像这样:

function checkExt() { 
    var fileInputs = document.querySelectorAll('input[type="file"]'); 
    var isValid = true; 
    var allowedFiles = [".pdf"]; 
    var regex = new RegExp(
    "([a-zA-Z0-9s_\\.-:])+(" + allowedFiles.join("|") + ")$" 
); 

    fileInputs.forEach(function(input) { 
    if (!regex.test(input.value.toLowerCase())) { 
     isValid = false; 
    } 
    }); 

    if (isValid) { 
    alert("only PDF files are allowed"); 
    } 

    return isValid; 
} 

这使您可以根据需要添加尽可能多的文件输入字段。