Ron
Ron

Reputation: 105

convert HTML file contents into a string in Javascript

I'm asking users to upload and HTML file, I would like to convert the contents of the HTML file into a string.

HTML file:

<form action="">
  <input type="file" name="pic" accept="html" id = "htmlFile">
</form>

JAVASCRIPT

function readTextFile(file) //this is all wrong I think
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}

Upvotes: 2

Views: 14114

Answers (1)

Mosh Feu
Mosh Feu

Reputation: 29277

If I understand you correctly, you can read the file after the input change with FileReader like this:

function readSingleFile(evt) {
  //Retrieve the first (and only!) File from the FileList object
  var f = evt.target.files[0]; 

  if (f) {
    var r = new FileReader();
    r.onload = function(e) { 
      var contents = e.target.result;
      alert( "Got the file.n" 
            +"name: " + f.name + "n"
            +"type: " + f.type + "n"
            +"size: " + f.size + " bytesn"
            + "contents:" + contents
           );  
    }
    r.readAsText(f);
  } else { 
    alert("Failed to load file");
  }
}

document.getElementById('htmlFile').addEventListener('change', readSingleFile, false);
<form action="">
  <input type="file" name="pic" accept="html" id="htmlFile">
</form>

Source

Upvotes: 2

Related Questions