2017-08-02 75 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; 
} 

這使您可以根據需要添加儘可能多的文件輸入字段。