Download file with a REST request needing headers and giving the content

All we need is an easy explanation of the problem, so here it is.

I am using AngularJs with a REST API. I don’t have the hand on the REST API.
I can store digital object with the API by sending a REST request.
I can get it also with a GET request.
The requests needs to have some specific headers.

My goal is to give the user a “download and save as” link.
For now on the click event i make the request :

    this.file = function (file) {
        var url = config.domain + 'file/' + file;

        var methods = resource(url, null, { 
            'get': {
                method:'GET', 
                headers:{   'Authorization' : user.auth, 
                            'secret-key' : user.secretkey}
            }
            transformResponse : function(data, headersGetter){
                                    return {content:data}; //transform octet stream into text, angular returns an array containing 1 character per element.
                                },
        });
        return methods;
    };

in the return body I have the file content (see below). I would like to download it. How is it possible ? Notice that I can’t store the file as a URL.

Would it be possible to open a window wich make the rest call with the good headers and save the file ?

EDIT

I need the solution to be able to work well with a 50Mo File.

example of a PDF file content I have :

%PDF-1.7
£´ÅÖçø
2 0 obj
[/ICCBased 3 0 R]
endobj
3 0 obj
<<
/Filter /FlateDecode 
/Length 2596 
/N 3 
>>
stream
xwTSÙϽ7½PÐkhRH
½H.*1   JÀ"6DTpDQ¦2(à£C±"Q±ëDÔqpId­ß¼yïÍß÷~k½ÏÝgï}ÖºüÂLX    ¡XáçÅg`ðlàp³³BøF|Ølø½º         ùû*Ó?Áÿ¹Y"1PçòøÙ\É8=W%·Oɶ4MÎ0JÎ"Y2Vsò,[|öe9ó2<ËsÎâeðäÜ'ã9¾`çø¹2¾&[email protected]Æoä±|N6(Ü.æsSdl-c(2-        ãyàHÉ_ðÒ/XÌÏËÅÎÌZ.$§&\SáÏÏMçÅÌ07#â1ØYárfÏüYym²";Ø8980m-m¾(Ô]ü÷v^îDøÃöW~
°¦eµÙúmi]ëP»ýÍ`/²¾u}qº|^RÄâ,g+«ÜÜ\Kk)/èïúC_|ÏR¾Ýïåaxó8t1C^7nfz¦DÄÈÎâpùæøþuü$¾/ED˦L         Lµ[È[email protected]øøÃþ¤Ù¹ÚøÐX¥[email protected]~(*     {d+Ðï}ÆGùÍÑûÏþ}W¸LþÈ$cGD2¸QÎìüZ4 [email protected]ê@èÀ¶À¸àA(q`1àD µ ­`'¨u     46ptcà48.Ë`ÜR0)ð
Ì@ÈRt CȲXäCP%[email protected]ë R¨ªê¡fè[è(tº
C· Qhúz#0   ¦ÁZ°l³`O8ÁÉð28.·Àp|îOÃàX
?§:¢0ÂFBx$  !«¤[email protected]Ú¤¹H§È[EE1PLÊ⢡V¡6£ªQP¨>ÔUÔ(j
õMFk¢ÍÑÎèt,:.FW Ðè³èô8ú¡c1L&³³³Ó9Æa¦±X¬:Öë
År°bl1¶
{{{;}#âtp¶8_\<N+ÄU
[.....]

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I think you could using blob, something like

var content=...the content of your request;
var mypdf = new Blob(content, {type : 'application/pdf'});

and check answer from “panzi” in this other question Using HTML5/Javascript to generate and save a file

(One character per element in the array seem pretty nice binary. Probably you don’t need to transform it. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data )

Method 2

Maybe you could do something like this?

var a = document.createElement('a');
a.href = 'data:attachment/pdf,' + encodeURI(data);
a.target = '_blank';
a.download = 'filename.pdf';
a.click();

You’d just have to make sure that data was in the correct format, which IIRC is base64.

Method 3

you can use this instead of above code :

var url = config.domain + 'file/' + file;
   var parameters = "Authorization=" + user.auth +
                    "&secret-key=" + user.secretkey;
   var reportParameters = url + encodeURIComponent(parameters);
   window.location.assign(reportParameters);

Method 4

Thanks everybody for helping find a solution.

I am not able to find a satisfying solution in javascript and client side application.
I am going to make a proxy class communicating with the API.

This will send the REST request with security headers and will give as response the file content.

This class will be called by a HTTP GET request, so the ‘save as’ process will be managed easily thanks to right response headers.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply