0

I am coding a website where i need to get a PDF, JPG or PNG from a user. When the user choose a file i want the name of the file to be shown. Furthermore I want to check if the file is a PDF, JPG or PNG instantly so the file cant be uploaded if it isn't such a file.

My code:

<style>
#file { display:none; }
</style>

<label for="file">  
    <div id="file-wrapper">  
        <input id="file" type="file" name="file" required/>
        <div class="button smallbtn">Choose file</div>
        <div id="filev">No file chosen</div>
    </div>
    </label>

    <script>   
       setInterval(function(){
            document.getElementById("filev").innerHTML = document.getElementById("file").value;
        }, 2000);
    </script>

1 Answer 1

1

Hope it helps!

var _validFileExtensions = [".jpg", ".jpeg", ".pdf", ".png"];

function ValidateInput(oInput) {
  if (oInput.type == "file") {
    var sFileName = oInput.value;
    if (sFileName.length > 0) {
      var blnValid = false;
      for (var j = 0; j < _validFileExtensions.length; j++) {
        var sCurExtension = _validFileExtensions[j];
        if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
          blnValid = true;
          break;
        }
      }

      if (!blnValid) {
        alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
        oInput.value = "";
        return false;
      }
    }
  }
  return true;
}
<style>
  #file {
    display: none;
  }
</style>

<label for="file">  
    <div id="file-wrapper">  
        <input id="file" type="file" name="file" onChange="ValidateInput(this);" />
        <div class="button smallbtn">Choose file</div>
        <div id="filev">No file chosen</div>
    </div>
    </label>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.