RaviMittal RaviMittal - 8 days ago 7
Javascript Question

Saving binary data as file using JavaScript from a browser

I am working on a business application using

angularJS
. One of my service method returning me a
byte[]
(inclding PDF file content) now i need to download this file as
PDF
to client machine using
JavaScript
.

How is that possible using HTML5 Apis or any JavaScript API?

I have used
window.atob(base64String)


JVBERi0xLjMNJeLjz9MNJVBERi1Xcml0ZXIuTkVUIGRiQXV0b1RyYWNrIEx0ZC4NMSAwIG9iag08PA0vVGl0bGUgKEludm9pY2UpDS9BdXRob3IgKFNlcnZpY2VNYW5hZ2VyUGx1cykNL0NyZWF0b3IgKFNlcnZpY2VNYW5hZ2VyUGx1cykNL0NyZWF0aW9uRGF0ZSAoRDoyMDE0MDUwNDE1MDQ0MiswNSczMCcpDS9Nb2REYXRlIChEOjIwMTQwNTA0MTUwNDQyKzA1JzMwJykNPj4NZW5kb2JqDTIgMCBvYmoNWy9QREYgL1RleHQgL0ltYWdlQ10NZW5kb2JqDTMgMCBvYmoNPDwNL1R5cGUgL1BhZ2VzDS9LaWRzIFsgNCAwIFIgNiAwIFIgXQ0vQ291bnQgMg0+Pg1lbmRvYmoNNCAwIG9iag08PA0vVHlwZSAvUGFnZSANL1BhcmVudCAzIDAgUiANL01lZGlhQm94IFsgMCAwIDU5NSA4NDIgXSANL1JvdGF0ZSAwDS9Db250ZW50cyA1IDAgUiANL1Jlc291cmNlcyA8PA0vUHJvY1NldFsvUERGL1RleHQvSW1hZ2VDXQ0vRm9udCA8PCANL0YwIDggMCBSIA0vRjEgMTAgMCBSIA0+Pg0+Pg0+Pg1lbmRvYmoNNSAwIG9iag08PCAvTGVuZ3RoIDEyOTkgL0ZpbHRlciAvRmxhdGVEZWNvZGUgPj4Nc3RyZWFtDQp4nJVZTW/jNhC9+1cQ6KU9rEJKpETllk02LdC0+bCLXAIUqq0kahxpK8vJ5t+XlCxpyKEoJw6CxczjzPO8ITngnlxSElGyeiQLSvSnflp8XS1CQUkiQ7LaLH6+v777nVzfXXy7+4Ws/l18W5HFiVrFul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TQ5ODk0NkJFNEVCRTg1M0VDQkQ5ODhDNUNEPl0NPj4Nc3RhcnR4cmVmDTUwMjMNJSVFT0YN


but getting this following error
Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.

Answer

This is possible if the browser supports the download property in anchor elements.

var sampleBytes = new Int8Array(4096);

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');


JSFiddle: http://jsfiddle.net/VB59f/2