0

I saw a post How do I read in a local text file with javascript?

I want to add a button to simulate an upload. So my consideration is set a watcher to onclick in onchange processing, is it possible?

Here is jsfiddle

js

function readMultipleFiles(evt) {
//Retrieve all the files from the FileList object
var files = evt.target.files;

if (files) {
    for (var i = 0, f; f = files[i]; i++) {
        alert(f);
        var r = new FileReader();
        r.onload = (function (f) {
            return function (e) {
                var contents = e.target.result;
                alert(contents);
            };
        })(f);
        r.readAsText(f);
      }
    } else {
      alert("Failed to load files");
    }
}
document.getElementById('fileinput').addEventListener('change', readMultipleFiles, false);

html

<input type="file" id="fileinput" multiple />
Community
  • 1
  • 1
Sarotti
  • 65
  • 1
  • 3
  • 10

1 Answers1

0

Instead of the change handler, add a button and add a click handler

<input type="file" id="fileinput" multiple />
<button id="read">Read</button>

then

jQuery(function ($) {
    function readMultipleFiles(input) {
        //Retrieve all the files from the FileList object
        var files = input.files;

        if (files && files.length) {
            for (var i = 0, f; f = files[i]; i++) {
                var r = new FileReader();
                r.onload = (function (f) {
                    return function (e) {
                        var contents = e.target.result;
                        alert(contents);
                    };
                })(f);
                r.readAsText(f);
            }
        } else {
            alert("Failed to load files");
        }
    }

    var fileIn = $('#fileinput')[0];
    $('#read').click(function () {
        readMultipleFiles(fileIn)
    })
})

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531