Domanda

Is there anyway to download a text file and display its contents using HTML5/JavaScript? I'd prefer to save it to a memory location, but saving it to a temporary file would be a second option.

-- Updated --

As per the statement below. Here's what I've got so far using AngularJS acquiring a file from an Atmos ObjectStore. It's not clear to me how to present the file contents.

var app = angular.module('MyTutorialApp',[]);

app.controller("MainController", function($scope, $http) {

    console.log("starting download");
    $scope.downloadedFile = null;

    var config = {headers:  {
        'Accept': '*/*'
    }};

    $http.get('https://some_path/theFile.txt?uid=myUUID&expires=1396648771&signature=mySignature', config)
        .success(function(data) {
            $scope.downloadedFile = data;
            console.info(data);
            console.log("finished download");
        });
});
È stato utile?

Soluzione

You can do that with HTML5 + Javascript! I've made this example:

HTML code:

<input id="myFile" type="file" value="Select a text file" />
<br />
<h3>Results:</h3>
<div id="myContents"></div>

Javascript code:

$("#myFile").on("change", function(e) {
    var reader = new FileReader();
    reader.onload = function(e) {
        $("#myContents").html(this.result.replace(/\n/g, "<br />"));
    };
    reader.readAsText(e.target.files[0]);
});

EDIT:

You've edited your question, and now I see you want to take the TXT file from your server. Well, I don't use Angular.JS, but in jQuery, it would be something like:

HTML:

<div id="myServerContents"></div>

Javascript/jQuery:

$.ajax({
    url: "myFile.txt",
    data: {},
    async: false,
    success: function (response) {
        $("#myServerContents").html(response.replace(/\n/g, "<br />"));
    },
    dataType: "text/plain"
});

Altri suggerimenti

Fetching txt file content from a client side could be done in many ways, one would be to use JQuery .get() or .load(), but I'm not sure if you use JQuery.

Another simple option is to use iframe, take this example:

<iframe src='http://yourSite.com/yourDir/logs/myTextFile.txt' />

JSFIDDLE DMEO

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top