How to read binary file content in Javascript

14

How to read binary file content in Javascript?

    
asked by anonymous 15.05.2015 / 19:50

1 answer

20

It depends on where you need to read the file if you want to read from the user's machine, you will need File API combined with <input type="file"> .

Read a file:

function LerArquivo(file, done, fail) {
    var reader = new FileReader;
    reader.onload = function(evt) {
        done(evt.target.result);
    };
    reader.onerror = function(evt) {
        fail();
    };
    reader.readAsText(file);
}

var response = document.getElementById("response");

document.getElementById("test").onchange = function() {
    if (this.files.length === 1) {
        LerArquivo(this.files[0], function(resposta) {
             response.value = resposta;
        }, function() {
             response.value = "Falha ao ler o arquivo";
        });
    }
};
<input type="file" id="test">
<textarea style="width:100%; height: 400px;" id="response"></textarea>

Read multiple files:

  

Note that you must add the multiple attribute to <input>

function LerArquivo(file, done, fail) {
    var reader = new FileReader;
    var name = file.name;

    reader.onload = function(evt) {
        done(name, evt.target.result);
    };
    reader.onerror = function(evt) {
        fail(name);
    };
    reader.readAsText(file);
}

document.getElementById("test").onchange = function() {
    if (this.files.length !== 0) {
        for (var i = 0, j = this.files.length; i < j; i++) {
            LerArquivo(this.files[i], function(nome, resposta) {
                console.log(nome, resposta);
            }, function(nome) {
                console.log("Falha ao ler:", nome);
            });
        }
    }
};
<input type="file" multiple id="test">

Note that you can read the file in different ways:

  • FileReader.readAsArrayBuffer() returns the result as ArrayBuffer
  • FileReader.readAsDataURL() returns the result as Base64 with Data URI Scheme
  • FileReader.readAsText() returns the result as text and you should set the encoding as needed.
  • FileReader.readAsBinaryString() returns the result byte to byte ( This is deprecated and will be removed so it is preferable to use readAsArrayBuffer or readAsDataURL )

Documentation: link

  

Although not considered to refer to this as part of HTML5, it is still not correct, HTML5 is one thing and Javascript APIs are something else. HTML5 actually consists of new tags and features in HTML and the new Javascript APIs interact with these new Html5 features.

    
10.03.2016 / 18:45