Search code examples
javascripthtmlangularjsemc

How to download and display a text file using HTML5/Javascript?


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");
        });
});

Solution

  • 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"
    });