Geoff Nunes
Geoff Nunes

Reputation: 67

capture file into javascript variable instead of downloading it

I am writing a app that visits a web site that can give me a link to a file, like this: http://www.thrustcurve.org/download.jsp?id=2199

If I visit this link, a small text file is downloaded. What I would like to do instead is to capture this text into a javascript variable so I can search around in it and extract the data I need.

Is this even possible?

Further details: although I am old and have lots of programming experience, I am a total noob in the javascript/web/server/modern space (think FORTRAN 77). I now teach high school physics and am trying to build a web-based rocket simulator for my students to use on their chromebooks. The creator of thrustcurve.org has generously made data about rocket motors available on the web, but I need some bits that can only be found inside these little text files. Maybe it would be possible to work with the downloaded files on the chrome books, but I really have no idea how to begin there. If you are patient enough to have read this far, you can see the kind of javascript I have been able to accomplish at noragulfa.com

Upvotes: 2

Views: 917

Answers (1)

Victor
Victor

Reputation: 5769

You can use XMLHttpRequest to perform HTTP requests, but due to security restrictions the browser blocks requests to “external domains” (thus, you can download files only from your domain). For more info, read about Cross-Origin Resource Sharing (CORS).

To solve your task, you have several options:

1) Download required files from thrustcurve.org and store them on your server. This is the best option since you will not be dependent on an external server (besides, hotlinking may upset the thrustcurve.org owner). In this case XMLHttpRequest will be able to access files using relative URLs:

var url = '/thrustcurve-downloads/Estes_A8.eng';

2) Contact the thrustcurve.org owner and ask him to enable Access-Control-Allow-Origin from anywhere. In this case XMLHttpRequest will be able to access files using full URLs:

var url = 'http://www.thrustcurve.org/download.jsp?id=2199';

3) Create a proxy that passes HTTP requests to thrustcurve.org. For example, since you are using nginx, you can simple add the following to your configuration file:

location /thrustcurve {
    proxy_pass http://www.thrustcurve.org/;
}

In this case XMLHttpRequest will be able to access files using relative URLs:

var url = '/thrustcurve/download.jsp?id=2199';

4) Use third-party proxies (not a very reliable solution, but great for tests). As an example, I will use this option.

var url = 'http://cors-anywhere.herokuapp.com/http://www.thrustcurve.org/download.jsp?id=2199';

var xhr = new XMLHttpRequest();
xhr.onload = function () {
	console.log(xhr.response);
};

xhr.open('GET', url);
xhr.responseType = 'text';
xhr.send();

UPD: A full example how to download files using a XMLHttpRequest and PHP.

1) Create the file thrustcurve.php on your root server with the following contents:

<?php

// Change this to FALSE if don't want to store files locally
$store_files_locally = true;

$id = (int) filter_input(INPUT_GET, 'id');
if ($id > 0) {
    if ($store_files_locally) {
        // Specify the directory where you want to store engine files
        // It will create the directory if it doesn't exist
        $dir = __DIR__ . '/thrustcurve-downloads';
        if (!is_dir($dir) && !mkdir($dir, true, 0777)) {
            http_response_code(500);
            die('Cannot create the downloads directory');
        }

        // If file exists, load the engine from the local file
        $file = "{$dir}/{$id}.eng";
        if (is_file($file)) {
            $engine = file_get_contents($file);
            die($engine);
        }
    }

    // Download the engine file from the remote server
    $url = "http://www.thrustcurve.org/download.jsp?id={$id}";
    $engine = trim(@file_get_contents($url));

    // The downloaded file is considered valid engine only if it starts with semicolon
    if (strpos($engine, ';') === 0) {
        if ($store_files_locally) {
            file_put_contents($file, $engine);
        }

        die($engine);
    }
}

http_response_code(404);
echo "File #{$id} not found";

2) To download files using JavaScript, use the following:

var xhr = new XMLHttpRequest();
xhr.onload = function () {
    if (xhr.status === 200) {
        console.log(xhr.response);
    } else {
        console.error(xhr.response);
    }
};

xhr.open('GET', '/thrustcurve.php?id=2198');
xhr.responseType = 'text';
xhr.send();

Upvotes: 3

Related Questions