0

I want to be able to store the contents from an imported text file in a JS variable. Could someone please show me how I would go about doing this by using the JSFiddle example I have created? https://jsfiddle.net/495v0bxf/. Currently in the JSFiddle, you can select a document and display the contents.

I know the content can be accessed in the reader variable under 'result':

var reader = new FileReader();
console.log("reader: ", reader);

But I want the content to be stored in say:

var txtContent = 
Garrett
  • 241
  • 3
  • 7
  • 16

2 Answers2

2

As in your example, you need to store evt.target.result in the variable.

var reader = new FileReader();
var txtContent;

var doSomeStuff = function () {
    console.log("The text content was " + txtContent);
};

// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
    if (evt.target.readyState == FileReader.DONE) { // DONE == 2
        txtContent = evt.target.result;
        doSomeStuff();
    }
};

As you can see, when doSomeStuff is called, txtContent is populated with the text loaded from the file.

James Monger
  • 10,181
  • 7
  • 62
  • 98
  • How would I get it to save to the variable as soon as its text file is selected? I've updated the JSfiddle https://jsfiddle.net/495v0bxf/2/ – Garrett Sep 23 '16 at 12:16
0

This will help you.. It has all the examples which will guide you to read the content and store in variable.

http://www.html5rocks.com/en/tutorials/file/dndfiles/

Thanks