How Filereader.Readastext in HTML5 File API Works

FileReader Error from How FIleReader.readAsText in HTML5 File API works

When the code

var input = document.getElementById('#fileInput');
input.addEventListener("change", addDoc);

fails with the message Uncaught TypeError: Cannot read property 'addEventListener' of null, it follows that document.getElementById('#fileInput') returns null.

This, in turn, means that there was no element with the ID '#fileInput' at the time the code ran. This is true, you only have a similarly id-ed element with id="fileInput", without a leading # character. So set input like

var input = document.getElementById('fileInput');

or

var input = document.querySelector('#fileInput');

In addition, make sure that the JavaScript code does not run too early. Normally, everything that depends on the DOM should only be called once the DOMContentLoaded event has fired, especially if your script tags located are in the document head. Otherwise, when the JavaScript runs, the DOM may not include the desired elements yet.

HTML5 File API: How to see the result of readAsText()

readAsText is asynchronous, so you would need to use the onload callback to see the result.

Try something like this,

var fr = new FileReader();
fr.onload = function(e) {
// e.target.result should contain the text
};
fr.readAsText(file);

Further information here,

https://developer.mozilla.org/en-US/docs/DOM/FileReader

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.

HTML5 JS Get .txt File Text

The proper way to get the result of FileReader is
reader.onload=function() {/*retrieve reader.result here*/};, and you can insure that you can retrieve the result of the reader reader.result once the file you're trying to load is successfully loaded.

To invoke the reader, call reader.readAsText(fileInput).

HTML5 FIle API: Security Error while reading a file

If you're testing an app from file://, you can run Chrome with the following flags: --allow-file-access-from-files --allow-file-access. This should only be used for testing purposes.

Read File stored on some URL using HTML5 File API

You can download remote files over XMLHttpRequest, and process them as Blob. Then upload it to another server. The upload has to be over XMLHttpRequest. It relies on the browser's implementation of XHR Level 2. This link contains the code snippets you will need:

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

It has both snippets for downloading remote file as a Blob and uploading a Blob to a server.

filereader api on big files

Your application is failing for big files because you're reading the full file into memory before processing it. This inefficiency can be solved by streaming the file (reading chunks of a small size), so you only need to hold a part of the file in memory.

A File objects is also an instance of a Blob, which offers the .slice method to create a smaller view of the file.

Here is an example that assumes that the input is ASCII (demo: http://jsfiddle.net/mw99v8d4/).

function findColumnLength(file, callback) {
// 1 KB at a time, because we expect that the column will probably small.
var CHUNK_SIZE = 1024;
var offset = 0;
var fr = new FileReader();
fr.onload = function() {
var view = new Uint8Array(fr.result);
for (var i = 0; i < view.length; ++i) {
if (view[i] === 10 || view[i] === 13) {
// \n = 10 and \r = 13
// column length = offset + position of \r or \n
callback(offset + i);
return;
}
}
// \r or \n not found, continue seeking.
offset += CHUNK_SIZE;
seek();
};
fr.onerror = function() {
// Cannot read file... Do something, e.g. assume column size = 0.
callback(0);
};
seek();

function seek() {
if (offset >= file.size) {
// No \r or \n found. The column size is equal to the full
// file size
callback(file.size);
return;
}
var slice = file.slice(offset, offset + CHUNK_SIZE);
fr.readAsArrayBuffer(slice);
}
}

The previous snippet counts the number of bytes before a line break. Counting the number of characters in a text consisting of multibyte characters is slightly more difficult, because you have to account for the possibility that the last byte in the chunk could be a part of a multibyte character.

HTML5 File API read as text and binary

2022 update: See explanation below for why the OP was seeing what they were seeing, but the code there is outdated. In modern environments, you'd use the methods on the Blob interface (which File inherits):

  • arrayBuffer for reading binary data (which you can then access via any of the typed arrays)
  • text to read textual data
  • stream for getting a ReadableStream for handling data via streaming (which allows you to do multiple transformations on the data without making multiple passes through it and/or use the data without having to keep all of it in memory

Once you have the file from the file input (const file = fileInput.files[0] or similar), it's literally just a matter of:

await file.text(); // To read its text
// or
await file.arrayBuffer(); // To read its contents into an array buffer

(See ReadableStream for an example of streams.)

You might access the array buffer via a Uint8Array (new Uint8Array(buffer)).

Here's an example of text and arrayBuffer:

const $ = id => document.getElementById(id);

const fileInput = $("fileInput");
const btnRead = $("btnRead");
const rdoText = $("rdoText");
const contentsDiv = $("contents");

const updateButton = () => {
btnRead.disabled = fileInput.files.length === 0;
};

const readTextFile = async (file) => {
const text = await file.text();
contentsDiv.textContent = text;
contentsDiv.classList.add("text");
contentsDiv.classList.remove("binary");
console.log("Done reading text file");
};

const readBinaryFile = async (file) => {
// Read into an array buffer, create
const buffer = await file.arrayBuffer();
// Get a byte array for that buffer
const bytes = new Uint8Array(buffer);
// Show it as hex text
const lines = [];
let line = [];
bytes.forEach((byte, index) => {
const hex = byte.toString(16).padStart(2, "0");
line.push(hex);
if (index % 16 === 15) {
lines.push(line.join(" "));
line = [];
}
});
contentsDiv.textContent = lines.join("\n");
contentsDiv.classList.add("binary");
contentsDiv.classList.remove("text");
console.log(`Done reading binary file (length: ${bytes.length})`);
};

updateButton();

fileInput.addEventListener("input", updateButton);

btnRead.addEventListener("click", () => {
const file = fileInput.files[0];
if (!file) {
return;
}
const readFile = rdoText.checked ? readTextFile : readBinaryFile;
readFile(fileInput.files[0])
.catch(error => {
console.error(`Error reading file:`, error);
});
});
body {
font-family: sans-serif;
}
#contents {
font-family: monospace;
white-space: pre;
}
<form>
<div>
<label>
<span>File:</span>
<input type="file" id="fileInput">
</label>
</div>
<div>
<label>
<input id="rdoText" type="radio" name="format" value="text" checked>
Text
</label>
<label>
<input id="rdoBinary" type="radio" name="format" value="binary">
Binary
</label>
</div>
<div>
<input id="btnRead" type="button" value="Read File">
</div>
</form>
<div id="contents"></div>


Related Topics



Leave a reply



Submit