简体   繁体   中英

java script: How can I read html file and load its content to a div

I'm trying to read a html file from client computer and load its body content to a div. However, I'm not sure about the correct way to do that. I tried apply these to an uploaded file:

   $('#theFile').on("change", function () {
        var file = (this).files[0];
        var reader = new FileReader();
        reader.onload = function (e) {
            str = e.target.result;
            slides = new Array(1);
            var pattern = new RegExp(/<body[^>]*>((.|[\n\r])*)<\/body>/im);
            var res = str.match(pattern).join();
            console.log(res);
            $('#slide').html(res);
            slides[0] = res;
        };
        reader.readAsText(file);
    });

The res is an array with 3 elements so I joined them together. Is there better solutions which don't engage with regular expressions?

Add a file-input element to the HTML page:

<input type="file" id="file" onchange="readTxT()"/>
And select sample.txt manually:

function readTxT(){
  var reader = new FileReader();
  var files=document.getElementById('file').files;
  var f = files[0];
  reader.onload = function(e) {
    var text = reader.result;
    $(".diagram").text(text);
  }
  reader.readAsText(f);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM