Open Input File with Javascript

Asked

Viewed 1,575 times

2

I have a form with only one input of the kind file and a button submit.

I want to get the contents of that file txt and save in a variable, this without giving refresh and without doing upload from the archive before, all with Javascript/jQuery.

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 to input type=file in the 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>

Browser other questions tagged

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