File.getAsText

  • Revision slug: Web/API/File.getAsText
  • Revision title: File.getAsText
  • Revision id: 400277
  • Created:
  • Creator: Sheppy
  • Is current revision? No
  • Comment page created, 137 words addedMoved From DOM/File.getAsText to Web/API/File.getAsText

Revision Content

Summary

Returns the file's contents as a DOMString in which the file's data is interpreted as text using a given encoding.

Example

// fileInput is a HTMLInputElement: <input type="file" id="myfileinput" multiple>
var fileInput = document.getElementById("myfileinput");

// files is a FileList object (similar to NodeList)
var files = fileInput.files;

// object for allowed media types
var accept = {
    binary : ["image/png", "image/jpeg"],
    text :   ["text/plain", "text/css", "application/xml", "text/html"]
};

var file;

for (var i = 0; i < files.length; i++) {

    file = files[i];

    // if file type could be detected
    if (file !== null) {

        if (accept.binary.indexOf(file.mediaType) > -1) {

            // file is of type text, which we accept
            // make sure it's encoded as utf-8
            var data = file.getAsText("utf-8");
            // modify data with string methods


        } else if (accept.binary.indexOf(file.mediaType) > -1) {
            // binary
        }

    }
}

Revision Source

<h3 id="Summary">Summary</h3>
<p>Returns the file's contents as a <code>DOMString</code> in which the file's data is interpreted as text using a given encoding.</p>
<h3 id="Example">Example</h3>
<pre class="eval">// fileInput is a HTMLInputElement: &lt;input type="file" id="myfileinput" multiple&gt;
var fileInput = document.getElementById("myfileinput");

// files is a FileList object (similar to NodeList)
var files = fileInput.files;

// object for allowed media types
var accept = {
    binary : ["image/png", "image/jpeg"],
    text :   ["text/plain", "text/css", "application/xml", "text/html"]
};

var file;

for (var i = 0; i &lt; files.length; i++) {

    file = files[i];

    // if file type could be detected
    if (file !== null) {

        if (accept.binary.indexOf(file.mediaType) &gt; -1) {

            // file is of type text, which we accept
            // make sure it's encoded as utf-8
            var data = file.getAsText("utf-8");
            // modify data with string methods


        } else if (accept.binary.indexOf(file.mediaType) &gt; -1) {
            // binary
        }

    }
}</pre>
Revert to this revision