6

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?

Sycren
  • 539
  • 2
  • 5
  • 15

2 Answers2

12

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);
Brian Campbell
  • 322,767
  • 57
  • 360
  • 340
  • thanks, It reads a txt file fine now. Any idea why when reading an xml file it only prints the most outermost children? – Sycren Apr 21 '11 at 16:05
  • @Sycren Because you are writing it into the document using `innerHTML`, which will attempt to parse the XML as if it were HTML. If you want to insert it it as plain text so you can see all of the markup, then you should use something like `span.appendChild(document.createTextNode(e.target.result))` – Brian Campbell Apr 21 '11 at 16:14
  • 1
    I was hoping that it would be possible to load an xml file into the page and then use jquery to parse the structure. The xml is an sbml file (Systems biology markup language). This would then be used to create a tool for easy editing of the file. Would this be possible? – Sycren Apr 21 '11 at 17:08
  • 1
    @Sycren There's no standard way of parsing a string as XML. However, Mozilla's [DOMParser](https://developer.mozilla.org/en/DOM/DOMParser) has become a de-facto standard, supported by Firefox, Safari, Chrome, Opera, and IE 9. For old versions of IE, you can use [MSXML.DOMDocument](http://msdn.microsoft.com/en-us/library/aa468547.aspx), and in old versions of other browsers you can emulate it with an XMLHttpRequest of a `data:` URI. [Here's an example](https://sites.google.com/a/van-steenbeek.net/archive/explorer_domparser_parsefromstring) of how to support all three techniques. – Brian Campbell Apr 21 '11 at 17:41
  • Thankyou, parser=new DOMParser(); xmlDoc=parser.parseFromString(e.target.result,"text/xml"); from the first link corrected this for me – Sycren Apr 21 '11 at 19:30
0

This can be done quite easily using javascript XMLHttpRequest() class:

function FileHelper()
{}
{
    FileHelper.readStringFromFileAtPath = function(pathOfFileToReadFrom)
    {
        var request = new XMLHttpRequest();
        request.open("GET", pathOfFileToReadFrom, false);
        request.send(null);
        var returnValue = request.responseText;

        return returnValue;
    }
}

...

var text = FileHelper.readStringFromFileAtPath ( "mytext.txt" );
fedorqui
  • 275,237
  • 103
  • 548
  • 598
user3375451
  • 187
  • 1
  • 2