3

I am using Firefox version 14.0.1. I need to filter the upload file window to show up only .txt files.

My browser is not supporting only for text files(text/plain). I can restrict image files by specifying this format ("image/*"). But I need to filter only text files in File Selector window.

Is there any problem with my browser?

gideon
  • 19,329
  • 11
  • 72
  • 113
Deva
  • 139
  • 3
  • 9

2 Answers2

4

Simply do this...

$("#form").submit(function(e) {
  e.preventDefault();
  var checkUploadFileExtension =  $('input[type=file]').val().replace(/C:\\fakepath\\/i, '').split('.').pop();

  if(checkUploadFileExtension === 'txt') {
    alert("Success Uploaded!");
    //Do Something
  } else {
    alert("Please upload text file only");
    //Show error
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<form id="form" name="form" method="post">
  <input name="file" id="file" type="file" accept="text/*" />
  <button class="btn operations-btn btn-default" id="submit">Upload</button>
</form>

I hope, will help my post. Thank you

2

So according to the MDN reference on the input element accept=[MIME Type] is unimplemented in Gecko and currently you can only do : accept=image|audio|video

One way you could do this is a server side check for the type on the asp.net-mvc controller.

But a nicer way would be to do it on the client with some javascript: Something like this:

<script>
function checkExt() {
 if(document.mainForm.myfile.value.lastIndexOf(".txt")==-1) {
    alert("Please upload only .txt extention file");
    return false;
 }
}
</script>
<form name="mainForm">
<input type="file" name="myfile" onchange="checkExt();"/>
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

See it running here: http://jsfiddle.net/Egr9V/

If your using JQuery you could make your code slicker or use the Validation plugin as described in this post: How to have jQuery restrict file types on upload?

Community
  • 1
  • 1
gideon
  • 19,329
  • 11
  • 72
  • 113
  • Yes i did what you have posted already. but the thing is i should filter to only text files to show up on window. (text/plain) is working in chrome. its not working in Firefox. – Deva Aug 20 '12 at 07:01
  • @Deva Firefox/Gecko does support `text/plain`. I updated my answer. – gideon Aug 20 '12 at 07:15
  • Is that Gecko is an SDK. How can i make it workable with Firefox. Is there any procedure to follow up? – Deva Aug 20 '12 at 07:32
  • @Deva [Gecko](http://en.wikipedia.org/wiki/Gecko_(layout_engine)) is the engine firefox uses to render and layout html. The feature you are looking for hasn't been implemented yet. You could keep track of the [bug page here](https://bugzilla.mozilla.org/show_bug.cgi?id=565274) – gideon Aug 20 '12 at 07:39