How to check the format and type of a text file?

1

I have an input file in which I have limited to only accept file whose format is a text file, with extension .txt .

I used the accept attribute for this, see:

accept=".txt"

However, I would like to know if it is possible to check using jQuery, the format and the type of the file in case the accept attribute fails?

Mcve

Example example:

function verificarArquivoTexto(arq)
{

}

$(
	function ()
  {
  	$('input:file').change(
    	function(e)
      {
      	var arq = $(this).val().split('\').pop();
        $('.arquivo').html(arq);
      }
    );
  }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><inputid="upload" type="file" name="file-upload" accept=".txt">
<div class="arquivo">

</div>
    
asked by anonymous 25.01.2018 / 21:48

2 answers

2

Not necessarily with jQuery, but rather with the% JavaScript native API like this:

$('input:file').change(function (e) {
    console.log("Tipo:", this.files[0].type);
});

If you are uploading multiple files

$('input:file').change(function (e) {
    for (var i = 0, j = files.length; i < j; i++) {
        console.log("Tipo:", this.files[i].type);
    }
});

Example:

    $('input:file').change(function (e) {
        console.log("Campo: ", this.name);
        console.log("Tipo: ", this.files[0].type);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="file" name="arquivo1">
<input type="file" name="arquivo2">
    
25.01.2018 / 21:59
3

Yes, it is possible. Just capture the values of the input.files attribute, it will return you an array of File and then just check.

const inputUpload = document.querySelector("#upload");

inputUpload.addEventListener("change", () => {
  
  for (let i = 0; i < inputUpload.files.length; i++) {
    if ( 
      inputUpload.files[i].name.match(/\.txt$/) && //Verifica se o nome do arquivo termina com .txt
      inputUpload.files[i].type == "text/plain" //Verifica o mimetype do arquivo
    ) {
      console.log( inputUpload.files[i].name + " é um txt" );
    } else {
      console.log( inputUpload.files[i].name +  "não é um txt" );
    }
  }
});
<input id="upload" type="file" name="file-upload" multiple >
    
25.01.2018 / 21:59