开发者

HTML5 File API: FileReader.readAsText() returns "undefined"

开发者 https://www.devze.com 2023-03-14 09:07 出处:网络
I use Chrome 12 on Mac OS X and I\'ve included jQuery 1.6.1 within the document. I try to read the contents of a file as text and save it in a data-object with the following function:

I use Chrome 12 on Mac OS X and I've included jQuery 1.6.1 within the document.

I try to read the contents of a file as text and save it in a data-object with the following function:

this.upload = function(file) {
    console.log('FileHandler.upload called with ' + file.name + '.');
    console.log(file);
    console.lo开发者_JAVA技巧g(this.reader);

    data = {
        content: this.reader.readAsText(file)
    }

    console.log('Content: ' + data.content);
}

"file" seams to be a valid file-object and "this.reader" is a fresh instance of type FileReader. This code creates the following console output:

http://cl.ly/1Y2b383G2F272x1m1P0N

HTML5 File API: FileReader.readAsText() returns "undefined"


That's not the way it works according to the docs. You should call the readAsText() function, and when it's completed the result is stored in .result.


i found this example in this page of the docs and it worked for me on the first try:

HTML:

<input type="file" onchange="previewFile()"><br>
<p class="content"></p>

JavaScript:

function previewFile() {
  const content = document.querySelector('.content');
  const [file] = document.querySelector('input[type=file]').files;
  const reader = new FileReader();

  reader.addEventListener("load", () => {
    // this will then display a text file
    content.innerText = reader.result;
  }, false);

  if (file) {
    reader.readAsText(file);
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消