3

I have an HTML file, which I want to read and append as HTML. I have tried the below codes but these codes are not working.

Approach 1:

var file = "abc.html";

var str = "";
var txtFile = new File(file);
txtFile.open("r");
while (!txtFile.eof) {
    // read each line of text
    str += txtFile.readln() + "\n";
}

$('#myapp').html(str);

Approach 2:

var file = "abc.html";
var rawFile = new XMLHttpRequest();
alert('33333333');
rawFile.open("GET", file, false);
alert('44444');
rawFile.onreadystatechange = function () {
    alert('5555555555');
    if (rawFile.readyState === 4) {
        alert('66666666666');
        alert(rawFile.readyState);

        if (rawFile.status === 200 || rawFile.status == 0) {
            var allText = rawFile.responseText;
            $('#myapp').html(allText);
            alert(allText);
        }
    }
}
rawFile.send(null);

In Approach 2, it not going into the onreadystatechange method.

I thought another approach that I will use all the abc.html file content as a string variable and do similar $('#myapp').html(allText);, but this looks very bad approach because later I need to do the same for other 10-15 files. So Could you guys help me out?

Note: My application is running in offline mode means I cannot use the internet.

I have tried this solution, but its also not working.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
  • 2
    Possible duplicate of [How to read a local text file?](https://stackoverflow.com/questions/14446447/how-to-read-a-local-text-file) – 31piy Aug 08 '18 at 13:19
  • 3
    Assuming by 'local file' you mean one stored on the client machine, then this is not possible. You cannot make an AJAX request to a local file. Try using a [`FileReader`](https://developer.mozilla.org/en-US/docs/Web/API/FileReader) instead, although you're still likely to have browser implementation support problems, inconsistencies and security problems – Rory McCrossan Aug 08 '18 at 13:20
  • you have to use FileReader.. – Nikhil Ghuse Aug 08 '18 at 13:21
  • @RoryMcCrossan yes stored on the client machine, but its part of my application only. – Vivek Nuna Aug 08 '18 at 13:24
  • I have an example to use with XML if you want i can put it here – Alvaro Alves Aug 08 '18 at 13:32
  • @AlvaroAlves, please put it – Vivek Nuna Aug 08 '18 at 13:35
  • @RoryMcCrossan its android webview, FileReader wont work – Vivek Nuna Aug 08 '18 at 13:43
  • I'm afraid you're pretty much out of luck then. – Rory McCrossan Aug 08 '18 at 13:46
  • @RoryMcCrossan FileReader will ask the user to upload the file? right? – Vivek Nuna Aug 08 '18 at 13:48
  • No, not at all. – Rory McCrossan Aug 08 '18 at 13:50
  • @RoryMcCrossan do you know how to use it for local file without uploading? – Vivek Nuna Aug 08 '18 at 13:57
  • Full instructions are in the link I provided in my first comment:https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications – Rory McCrossan Aug 08 '18 at 13:59
  • @viveknuna You would still have the user to select the file. Due to security reasons you can not access a file just by code. If that was possible all websites could access (most) files on a users pc which would be a very bad situation. – Mark Baijens Aug 08 '18 at 14:09
  • @MarkBaijens yes I completely agree with you and your point looks valid too. But if a file is part of your application in that case I think it should allow. – Vivek Nuna Aug 08 '18 at 14:10
  • @viveknuna Files part of your application should be stored on your server. Sessions, Cookies and localstorage will let you store some information though if you like that. – Mark Baijens Aug 08 '18 at 14:11
  • @viveknuna Also how do you know a file is part of a application? When it's created by the application? Then again, I don't want websites to create files on my local pc. It's bad enough that we have to clean up cookies from time to time. – Mark Baijens Aug 08 '18 at 14:17

2 Answers2

3

It is not possible as JavaScript is frontend framework and it doesn't have access to local file system.

But you can do diffrent method. -> you can serve that file in a local server and use http request with any backend framework.

0

I think you can adapt this pen to use as you wish: https://codepen.io/alvaro-alves/pen/wxQwmg?editors=1111

CSS:

#drop_zone {
        width:  100px;
        height: 100px;
        background: #000;
        background-repeat: no-repeat;
        background-size: 100px 100px;
        opacity: 0.5;
        border: 1px #000 dashed;
    }

HTML:

   <html>
  <body>
    <div id="drop_zone"   ondrop="dropHandler(event);" ondragover="dragOverHandler(event);">

            </div>
  </body>
</html>

JS:

//drop handler do XML
        function dropHandler(ev) {
            ev.preventDefault();

            var file, reader, parsed, emit, x, endereco;

            if (ev.dataTransfer.items) {
                for (var i = 0; i < ev.dataTransfer.items.length; i++) {
                    if (ev.dataTransfer.items[i].kind === 'file') {
                        file = ev.dataTransfer.items[i].getAsFile();
                        reader = new FileReader();
                        reader.onload = function() {
                            parsed = new DOMParser().parseFromString(this.result, "text/xml");
                            console.log(parsed);
                        };
                        reader.readAsText(file);
                        console.log('... file[' + i + '].name = ' + file.name);
                    }
                }
            } 

            removeDragData(ev)
        }

        function dragOverHandler(ev) {
          ev.preventDefault();
        }

        function removeDragData(ev) {
            if (ev.dataTransfer.items) {
                ev.dataTransfer.items.clear();
            } else {
                ev.dataTransfer.clearData();
            }
        }

You will just to handle the result.

Alvaro Alves
  • 308
  • 1
  • 3
  • 13