user3402702
user3402702

Reputation: 91

AngularJS, manage binary data

I want to download a file with angularjs (1.0.8) from a service Spring. I use a POST request because I have to pass a piece of HTML as parament, and browsers have limitation with length of query string. Here my code:

    $http({
        method: 'POST',
        url: '/export/pdf',
        data: "html=" + graphHtml.outerHTML,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        transformResponse: function(data, headersGetter){
            return data;
        }
    }).success(function(data) {
        console.log("Type '" + typeof(data) + "'");
        var hiddenElement = document.createElement('a');
        hiddenElement.href = 'data:application/pdf,' + data;
        hiddenElement.target = '_blank';
        hiddenElement.download = 'myFile.pdf';
        hiddenElement.click();
    });

I notice that the "data" received is already in "string" format! I see many (?) question point, and when type

    typeof(data)

i receive "string". I don't want this interpretation of my raw data. When i try to write data in a file, the size is double respect original file! I know it is for "string interpretation" of binary data that instead wanted read as binary. Has anyone a solution for see "data" in raw format and not as string?

Upvotes: 2

Views: 6474

Answers (2)

br2000
br2000

Reputation: 969

In a $http configuration object, specify

responseType : "blob"
to get response data returned in a binary format.

Otherwise, default response format is a String. For other choices for responseType, see AngularJS API reference.

Upvotes: 5

wayne
wayne

Reputation: 3410

set $http responseType in during config. and do something like this

Upvotes: 1

Related Questions