I'm trying to implement the download of a file through angular.js
The file comes from the server in binary format, the content type is application/octet-stream
The download is a GET using $resource
. Looking at the parameter passed to the callback (called content
below), it's an object containing the byte array and also a list of properties for $resource
.
Tried several ways to serve the file, but without success.
First of them:
...
var a = document.createElement('a');
a.href = "data:attachment/zip," + content;
a.download = zipName;
a.click();
In this case, the content of the zip file is [object Object]
I tried extracting the array from the object and joining everything into a string variable. The zip file in this case is way larger than the normal size. I had to set isArray: true
in the service that calls $resource
, otherwise there was no way to extract the byte content from the response object.
Here is how I did it:
var str = '';
for (var i = 0; i < content.length; i++) {
str += content[i][0];
}
...
var a = document.createElement('a');
a.href = "data:attachment/zip," + str;
a.download = zipName;
a.click();
Worth mentioning that calling encodeURI
on str
increments drastically the size of the downloaded zip, but the archive remains invalid.
I also tried creating a Blob
from the str
and setting the content type to application/octet-stream
, without any luck.
var blob = new Blob([str], {'type':"application/octet-stream"});
a.href = window.URL.createObjectURL(blob);
...
Don't know what I'm missing here, but it looks rather a problem of getting the right format for the byte array content and setting the correct href
before simulating the click for downloading.
Help is appreciated.
Thanks