Wednesday, February 10, 2010

Javascript : Validate file upload

Javascript code:

<script language="javascript">
function Checkfiles()
{
var fup = document.getElementById('upload_filename');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if(ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG" || ext == "doc")
{
return true;
}
else
{
alert("Upload Gif or Jpg images only");
fup.focus();
return false;
}
}
</script>

HTML form:

<form action="#" enctype="multipart/form-data" method="POST" onsubmit="return Checkfiles();">
<input type="file" id="upload_filename">
<input type="submit" value="Go!">
</form>

Or Ruby on Rails form:

<% form_for(@upload, :html => {:multipart => true, :onsubmit=>"return Checkfiles();"}) do |f| %>
<%= f.file_field :filename %>
<%= f.submit 'Create' %>
<% end %>


If you find this useful, would you like to buy me a drink? No matter more or less, it will be an encouragement for me to go further. Thanks in advance!! =)

8 comments:

  1. when i put a file with allowed extension it still gives me the same error

    ReplyDelete
  2. Nice script. its working fine.

    ReplyDelete
  3. How about if my fileupload type is in the content place ? any idea ?

    ReplyDelete
  4. Thanks for the Good Script, but can u give me the code for clearing Uploading image path, if it was not a valid extension.

    Thanks in Advance.

    ReplyDelete
  5. Hey Thanks for your code but it is not working for me..
    can your update your code...

    ReplyDelete