4

I have certain uploaded file code as following:

<script>
var input_file = document.getElementById('txt_list');
input_file.onchange = function() {
           var file = this.files[0];
           var reader = new FileReader();
           reader.onload = function(ev) {
                //myProcesses
           };
           reader.readAsText(file);
        };
</script>

How can I add new function to determine the type of uploaded file either txt, gif, etc? and if i have to validate it, what am i supposed to do then? Thanks in advance

Doni Andri Cahyono
  • 793
  • 5
  • 16
  • 28
  • possible duplicate of [How can i get file extensions with javascript?](http://stackoverflow.com/questions/190852/how-can-i-get-file-extensions-with-javascript) – Aleks G Oct 25 '12 at 09:27

3 Answers3

2

split the filename then second part will give you file extension

 return file .split('.').pop();

so if file is name.txt this will return txt

edit-

if you only have to check the filetype

var filetype=file.split('.').pop();
if(filetype!="txt"){
return false;
}
Buzz
  • 6,030
  • 4
  • 33
  • 47
2
return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;

or

return filename.split('.').pop();

please refer this link for more details -LINK

if u need a txt file only

save it to a variable and use a if else statement to verify it

var file=file.split('.').pop();


if (type=='txt'){
//do something
}else{
//do something
}
Community
  • 1
  • 1
Ghostman
  • 6,042
  • 9
  • 34
  • 53
1

You could use File.type to determine the mime type and check it against valid mime types.

Musa
  • 96,336
  • 17
  • 118
  • 137