2

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);
}
5
  • why you need to convert it into string ? Commented May 25, 2016 at 7:10
  • You didn't use jQuery. tag removed. Commented May 25, 2016 at 7:10
  • @RanjeetSingh I wan't to save the code in my database. Commented May 25, 2016 at 7:10
  • What do you want to achieve? What isn't working? Which errors are you getting? You're missing a lot in your question at the moment.. Commented May 25, 2016 at 7:11
  • Possible duplicate of Reading file contents on the client-side in javascript in various browsers Commented May 25, 2016 at 7:14

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.