How to determine file type using javascript with onload?

I have specific code for the downloaded file:

<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 to add a new function to determine the type of the downloaded file or txt, gif, etc.? and if I have to check it, what should I do then? thanks in advance

+4
source share
3 answers
 return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined; 

or

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

please refer to this link for more details - LINK

If you only need a txt file

save it in a variable and use the if else statement to check it

 var file=file.split('.').pop(); if (type=='txt'){ //do something }else{ //do something } 
+2
source

split the file name and the second part will give you the file extension

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

so if the file is name.txt , this will return txt

Edit-

if you only need to check the file type

 var filetype=file.split('.').pop(); if(filetype!="txt"){ return false; } 
+2
source

You can use File.type to determine the mime type and check for valid mime types.

+1
source

Source: https://habr.com/ru/post/1441971/


All Articles