Open Input File file with JavaScript [duplicate]

2

I have a form with only input of type file and a submit button.

I want to get the contents of this file txt and save it to a variable, without giving refresh and without doing upload of the file before, all with JavaScript / jQuery.

    
asked by anonymous 14.09.2017 / 03:08

1 answer

0

You can do this using the FileReader API . In the example below, you can save the contents of the selected TXT file in input type=file to variable texto :

<input type="file" id="files" name="files[]" />

<script>
function lerArquivoTxt(evt){
    var texto = "";
    var files = evt.target.files;
    for (var i = 0, f; f = files[i]; i++){
        var reader = new FileReader();
        reader.onload = function(event){
            var conteudo = event.target.result;
            var linhas = conteudo.split('\n');
            for(x=0;x<linhas.length;x++){
               texto += linhas[x];
            }
            alert(texto);
        };
        reader.readAsText(f);
    }
}
document.getElementById('files').addEventListener('change', lerArquivoTxt, false);
</script>
    
14.09.2017 / 03:56