Hello man
Hello man

Reputation: 117

How to read and display html file

I'm making a html editor but the problem is that when someone needs to view an html file i don't know how to display the text from the file.

<input type="file" onchange="previewFile()"><br>
<p id="txt1" src="blank.html"></p>
<script>
function previewFile() {
  const preview = document.getElementById('txt1');
  const file = document.querySelector('input[type=file]').files[0];
  const reader = new FileReader();

  reader.addEventListener("load", function () {
    // reads image file to a blob string
    preview.src = window.URL.createObjectURL(file);
  }, false);

  if (file) {
    reader.readAsDataURL(file);
  }
}
</script>

I used this script to read a file and display it by changing the paragraph src to a blob link, but looks like the paragraph dosn't get the text by a html text link using src. Is there a way to do it?

Upvotes: 0

Views: 1100

Answers (2)

Osama
Osama

Reputation: 27

The p tag does not support src attribute so the alternative solutions would be using element.innerHTML= text or you change the p tag into iframe

Upvotes: 0

n1md7
n1md7

Reputation: 3451

The paragraph does not have src attribute, You need to use either innerText or innerHTML to display the content.

function previewFile() {
  const content = document.querySelector('.content');
  const [file] = document.querySelector('input[type=file]').files;
  const reader = new FileReader();

  reader.addEventListener("load", () => {
    // this will then display a text file
    content.innerText = reader.result;
  }, false);

  if (file) {
    reader.readAsText(file);
  }
}
<input type="file" onchange="previewFile()"><br>
<p class="content"></p>

Upvotes: 2

Related Questions