HTML and CSS Reference
In-Depth Information
};
reader.readAsText(event.target.files[0]);
}
This is going to receive an event when the file is selected. The first thing this function will
do is create a new FileReader object. The FileReader is asked to read the file specified, and
then makes the contents available asynchronously, so we also need to add listeners for suc-
cess and failure. The onload listener will be called with the file contents; the onerror will
be called after any failure.
It is possible for the user to select multiple files at the same time; therefore the target of the
event will refer to an array of files. In our case we will ignore the fact this is an array and
simply choose the first file:
event.target.files[0]
Now add the following code in the init method of tasks-controller.js to listen for the user
selecting a file:
$('#importFile').change(loadFromCSV);
Once the listener has been added, try loading the file using the file chooser. (The code will
simply log the contents of the file for now).
If you examine the target of the event in the debugger you will see it makes available in-
formation about the file, including its name, type and modified date:
Determining the type of file that has been loaded can be important, since the FileReader
makes available a number of different mechanisms for reading different types of file. In
our case we have used readAsText , which makes the file contents available as a JavaScript
string, but the FileReader also supports the following:
• readAsBinaryString : The file contents is made available as a string, but each byte is rep-
resented by a number. If the data is textual this will be identical to readAsText.
• readAsDataURL : The file contents is made available as an encoded URL. If we load a
text document, the contents will be encoded in Base 64 encoding.
• readAsArrayBuffer : This can be used if you wish to access a specific part of a file.
Search WWH ::




Custom Search