Home / code

Check upload file

Writer: Christophe Wolfs
Published: 27 March 2008

Check the extentions of a upload file before actual submitting. This is a lot faster cause the (large) file doesn't have to be submitted to the server and then checked.
With the following script, you can only upload files : .gif, .jpg, .png.

<script language="javascript">
extArray = new Array(".gif",".jpg",".png");
function CheckAttach(form, file)
{
  allowSubmit=false;
  if(!file) return;

  while(file.indexOf("\\") != -1) file=file.slice(file.indexOf("\\") + 1);

  ext=file.slice(file.indexOf(".")).toLowerCase();
  for(var i=0;i<extArray.length;++i)
  {
        if(extArray[i]==ext)
        {
          allowSubmit=true;
          break;
        }
  }
  if(allowSubmit) form.submit();
  else alert("Please only upload files that end in types:  " + (extArray.join("  ")) + "\nPlease select a new file to upload and submit again.");
}
</script>

 Your form should look like this : 

<form method=post name='upform' action="somescript.cgi.asp.php" enctype="multipart/form-data">
<input type=file name='uploadfile'><br>
<input type=button name='Submit' value='Submit' onclick="CheckAttach(this.form,this.form.uploadfile.value)">

 

TOP