MdaG
MdaG

Reputation: 2730

How do I send data to my server and have it return it as a file

I cannot (afaik) create a file in my (javascript browser) client, so I want my server to do it before sending it back to the client which in turn should open a dialogue asking the user where to save the file.

How do I achieve this? Se below for a gist of what I currently have.

Client

$.ajax({
        type: 'POST',
        dataType: 'json',
        url: "http://localhost:5000/api/file",
        data: postData,
        contentType : 'application/json',
        success: function (responseData, textStatus, jqXHR) {
            // What do I put here?
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });

Server

router.post('/file', function (request, response) {
        var content = '';
        request.on('data', function (data) {
            content += data;
        });

        request.on('end', function () {
            var contentAsJson = JSON.parse(content);
            response.set("Content-Type", "text/plain");
            response.set("Content-Length", contentAsJson.text.length);
            response.set("Content-Disposition", 'attachment; filename='filename.txt');
            response.send(contentAsJson.text);
        });
    });

Upvotes: 0

Views: 109

Answers (1)

orcaman
orcaman

Reputation: 6581

You can in fact generate the binary stream of the file on the client using only JS, you do not have to post the data to the server.

First, create a binary representation of your data:

var str = <<your data as string>>
var uint = new Uint8Array(str.length);
for (var i = 0, j = str.length; i < j; ++i) {
    uint[i] = str.charCodeAt(i);
}

Then, request to save this as a file:

var sampleBytes = <<your typed array with the data>>;

var saveByteArray = (function () {
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    return function (data, name) {
        var blob = new Blob(data, {type: "octet/stream"}),
            url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = name;
        a.click();
        window.URL.revokeObjectURL(url);
    };
}());

saveByteArray([sampleBytes], 'example.txt');

Upvotes: 1

Related Questions