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

1

3 Answers 3

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

use this var file=file.split('.').pop(); see my updated answer
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;
}

2 Comments

var file = this.files[0]; return file .split('.').pop();
ok thanks. And maybe my next question, if it's not too much, what if I have to validate it? I need .txt only, for instance.
1

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.