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

Asked

Viewed 1,343 times

1

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

I used the attribute accept for this, see:

accept=".txt"

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


Mcve

Illustration:

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>

<input id="upload" type="file" name="file-upload" accept=".txt">
<div class="arquivo">

</div>

  • 1

    I would set aside to check front-end mimetype and focus more on file extension and weight. Even if you were trying to send a file. txt other than . txt, you can do this on the server. The front end has more function to avoid unnecessary requests to the server, but can be changed and a very low % of clients will waste time with it.

2 answers

3

Yes, it is possible. Just capture the values of the attribute input.files, 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 >

  • I selected a file . mp4 with extension . txt and validated as . txt.

  • @dvd According to the documentation, this happens because Js does not read the bytestream file. It takes this mimetype through the file extension. (Something similar to the methodMimeTypeMap.getMimeTypeFromExtension Android. For greater precision it is necessary to use the back-end.

  • Just an addendum: He can even use the Filereader API to read the contents of the file via JS, but I don’t know if it’s worth it. Mainly for large files.

2


Not necessarily with jQuery, but with the API File Javascript native, for example:

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

If 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>

<input type="file" name="arquivo1">
<input type="file" name="arquivo2">

  • I selected a file . mp4 with extension . txt and validated as . txt.

  • @dvd to solve this only by checking in the back end with php or other language through the "MAGIC" (if the operating system has support for MAGIC), in general the problem is implementation of the browsers that is anyway, works by "deduction".

  • Can’t you load the file in the browser? Type, the JS itself consume the file to be loaded?

  • 1

    @Jeffersonquesado he can yes read the contents of the file, just use the API FileReader, but the question is whether it is feasible, mainly with "large files".

  • @Valdeirpsr magic numbers are usually in the first 100 bytes of the file. So it would be passing this Octeto to a recognizer of magic numbers... (ok, now just missing the recognizer xD)

  • @Guillhermenascimento the this used to access the property files refers to the 'input:file'?

  • 1

    @cat yes, jQuery exclusively uses the .apply to change the context of the functions and events themselves, making it possible to refer to the specific DOM element, i.e. this will amount to <input> that triggered the change ;)

  • 2

    @Jeffersonquesado is very complex, not only for consumption but for the possibility of creating a MAGIC own for a front-end application, is possible but there is nothing ready and I would have to do everything from scratch, maybe in the future I create something in github and share. I added an example in the answer with jQuery to understand.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.