How to open a server file with javascript?

Asked

Viewed 3,385 times

1

I have this code that opens a local file, but I would like to open a server file without needing the input.

HTML:

<input type="file" onchange="run(this.files[0]);">

Javascript:

function run(file) {
    xyz.loadRomFromFile(file, function(result) {
        if (result) {
            for (var i = 0; i < runCommands.length; ++i) {
                runCommands[i]();
            }
            runCommands = [];
            xyz.runStable();
        }
    });
}
  • 1

    Friend, I don’t understand your question, but from what I understand, you really can’t open a file from the server with JS because he is Client-Side you can send a request for a language Server-Side and take the turnaround and work with him

2 answers

1

What you can do is an asynchronous call to the server. For example, to read a file html which is on the server, you can do so:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        // codigo
        document.getElementById('conteudoDoMeuArquivo').innerHTML = xhr.responseText;
    }
}

xhr.open('GET', 'caminho/para/meu/arquivo.html', true);
xhr.send();

If you are using the jQuery library, it gets a little easier =):

$.get('caminho/para/meu/arquivo.html', function(data) {
    // codigo
    $('#conteudoDoMeuArquivo').html(data);
});

0

It’s possible, but it’s not elementary.

As already mentioned, JS runs on the client, so you should do a service that gets the name of the file you want to open and returns its content. This service can be REST or it can be a server side script, like PHP, ASP, Node.js or Java Servlet. Anyway.

After that you should consume this service using http-request.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.