File fields

File fields were originally designed as a way to upload files from the browser's machine through a form.

In modern browsers, they also provide a way to read such files from JavaScript programs. A file field usually looks like a button labeled with something like "choose file" or "browse", with information about the chosen file next to it.

snippet
<input type="file">

<script>
var input = document.querySelector("input");
input.addEventListener("change", function() {
    if (input.files.length & gt; 0) {
        var file = input.files[0];
        console.log("You chose", file.name);
        if (file.type)
            console.log("Ithas type", file.type);
    }
});

The files property of a file field element is an array-like object (not a real array) containing the files chosen in the field.

Objects in the files property have properties such as name (the filename), size (the file's size in bytes), and type (the media type of the file, such as text/plain or image/jpeg).

You can read file content using the FileReader

snippet
<input type="file"multiple>

<script>
var input = document.querySelector("input");
input.addEventListener("change", function() {
    Array.prototype.forEach.call(input.files, function(file) {
        var reader = newFileReader();
        reader.addEventListener("load", function() {
            console.log("File", file.name, "startswith",
                reader.result.slice(0, 20));
        });
        reader.readAsText(file);
    });
});
</script>

Reading a file is done by creating a FileReader object, registering a "load" event handler for it, and calling its readAsText method, giving it the file we want to read. Once loading finishes, the reader's result property contains the file's content.

FileReaders also fire an "error" event when reading the file fails for any reason. The error object itself will end up in the reader's error property.

If you don't want to remember the details of yet another inconsistent asynchronous interface, you could wrap it in a Promise like this:

snippet
function readFile(file) {
    return new Promise(function(succeed, fail) {
        var reader = newFileReader();
        reader.addEventListener("load", function() {
            succeed(reader.result);
        });
        reader.addEventListener("error", function() {
            fail(reader.error);
        });
        reader.readAsText(file);
    });
}

It is possible to read only part of a file by calling slice on it and passing the result (a so-called blob object) to the file reader.

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +