5

I have some HTML as follows:

Select a file : <input type="file"><br><br>
Html Codes : <textarea id="displayHtml"></textarea><br><br>
<div id="displayPage">Display the Html Page here</div>

Now how would I browse an external HTML file from a local hard drive and display the page preview in the div #displayPage and get the HTML tags of the file into the textarea #displayHtml? I have no idea how to do this so please help.

My fiddle is here: https://jsfiddle.net/zm6ga2ev/1/

freginold
  • 3,946
  • 3
  • 13
  • 28

3 Answers3

2

You can do this using the File API within HTML5.

Here's a quick & dirty JS example:

function handleFileSelect(evt) {
  var file = evt.target.files[0]; // File inputs are an array - get the first element
  var reader = new FileReader();

  reader.onload = function(e) {
    // Render the supplied file
    document.getElementById('displayHtml').value = e.target.result
    document.getElementById('displayPage').innerHTML = e.target.result;
  };

  // Read in the HTML file.
  reader.readAsText(file);
};

document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);

JSFiddle: https://jsfiddle.net/8te1hyv9/

A decent explanation and more comprehensive examples of how everything fits together can be found at: http://www.html5rocks.com/en/tutorials/file/dndfiles/

Jimmy Carr
  • 21
  • 1
  • 4
  • @user5384372 in my opinion, this should be the accepted answer: this answer includes examples and links to external sources. the original question did not specify any external libraries and this answer does not use any. plus, this answer comes with a complete working example in the jsfiddle link. – Jonathan Sep 15 '18 at 12:15
1

Let the user upload the html file into your server .

Here is a nice way to upload files via ajax : http://code.tutsplus.com/tutorials/uploading-files-with-ajax--net-21077

Now , you can use this code to load html file into the div tag

document.getElementById("displayPage").innerHTML='<object type="text/html" data="page.html" ></object>';

Or simply use jquery .load() function

$("#displayPage").load("page.html");
dunstorm
  • 372
  • 6
  • 13
0

You just .load other page content into your div.

//Load full document
$('#displayPage').load('http://same-domain.com/next-page.html');

// You can use any CSS selector to load only part of page
$('#displayPage').load('http://same-domain.com/next-page.html #some-inner-id > *');

If #displayPage element is not found in DOM, than no request will be performed! If #some-inner-id is not found in request page DOM, than you get empty content.


Note

Loaded page must allow Cross-Origin request (usually it means same domain request). Look here for Cross-Origin requests.

Community
  • 1
  • 1
Justinas
  • 41,402
  • 5
  • 66
  • 96