HTML5 File api reading in XML file and displaying it on page?

I tried using the code below, modified by http://www.html5rocks.com/tutorials/file/dndfiles/ , to read in a text or XML file and display the content 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 (e, UTF-8); Does not work

reader.readAsDataURL (e); Displays a file in Base64

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

+6
source share
2 answers

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

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

Or you can simply completely abandon the encoding, in which case it will try to automatically detect UTF-16BE or LE, and if this is not one of them, it will use UTF-8 by default.

 reader.readAsText(f); 
+12
source

This can be done quite easily using the 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" ); 
0
source

Source: https://habr.com/ru/post/886395/


All Articles