Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 File api, reading in an xml/text file and displaying it on the page?

I have tried using the below code modified from http://www.html5rocks.com/tutorials/file/dndfiles/ to read in a text or xml file and display the contents below.

<!DOCTYPE html> 
<html> 
<head> 
    <title>reading xml</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
</head>
<body>
    <input type="file" id="files" name="files[]" multiple />
    <output id="list"></output>

    <script>
      function handleFileSelect(evt) {
        var files = evt.target.files; // FileList object

        // Loop through the FileList
        for (var i = 0, f; f = files[i]; i++) {

          var reader = new FileReader();

          // Closure to capture the file information.
          reader.onload = (function(theFile) {
            return function(e) {
              // Print the contents of the file
              var span = document.createElement('span');                    
              span.innerHTML = ['<p>',e.target.result,'</p>'].join('');
              document.getElementById('list').insertBefore(span, null);
            };
          })(f);

          // Read in the file
          //reader.readAsDataText(f,UTF-8);
          reader.readAsDataURL(f);
        }
      }

      document.getElementById('files').addEventListener('change', handleFileSelect, false);
    </script>
</body>

reader.readAsDataText(f,UTF-8); Does not work

reader.readAsDataURL(f); Displays the file in Base64

How can I get a text file to be displayed on the page?

like image 261
Sycren Avatar asked Apr 21 '11 12:04

Sycren


People also ask

How can you load XML data into an HTML page?

Content as XML string Most of the details of the code are in the script code. Internet Explorer uses the ActiveXObject("Microsoft. XMLDOM") to load XML data into a DOM object, other browsers use the DOMParser() function and parseFromString(text, 'text/xml') method.

Is used to fetch the data from the XML file?

The page uses the XMLHttpRequest (JavaScript) object to fetch the XML file (sample. xml) then parses it in JavaScript and creates the chart. The function that parses the XML response and then uses the data to create the chart is shown below and called myXMLProcessor() (it's the XMLHttpRequest callback function).


1 Answers

You need to pass in the encoding as a string; put quotes around the UTF-8. Also, it's readAsText, not readAsDataText:

reader.readAsText(f,"UTF-8");

Or you can just leave the encoding off entirely, in which case it will try to auto-detect UTF-16BE or LE, and if it's not one of those, it will just use UTF-8 by default.

reader.readAsText(f);
like image 105
Brian Campbell Avatar answered Sep 20 '22 13:09

Brian Campbell