最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Download file with a REST request needing headers and giving the content - Stack Overflow

programmeradmin2浏览0评论

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¾&ctI@Æ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µ[ÈB@øøÃþ¤Ù¹ÚøÐX¥!@~(*     {d+Ðï}ÆGùÍÑûÏþ}W¸LþÈ$cGD2¸QÎìüZ4 E@ê@èÀ¶À¸àA(q`1àD µ ­`'¨u     46ptcà48.Ë`ÜR0)ð
Ì@ÈRt CȲXäCP%CBH@ë R¨ªê¡fè[è(tº
C· Qhúz#0   ¦ÁZ°l³`O8ÁÉð28.·Àp|îOÃàX
?§:¢0ÂFBx$  !«¤i@Ú¤¹H§È[EE1PLÊ⢡V¡6£ªQP¨>ÔUÔ(j
õMFk¢ÍÑÎèt,:.FW Ðè³èô8ú¡c1L&³³³Ó9Æa¦±X¬:Öë
År°bl1¶
{{{;}#âtp¶8_\<N+ÄU
[.....]

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¾&ctI@Æ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µ[ÈB@øøÃþ¤Ù¹ÚøÐX¥!@~(*     {d+Ðï}ÆGùÍÑûÏþ}W¸LþÈ$cGD2¸QÎìüZ4 E@ê@èÀ¶À¸àA(q`1àD µ ­`'¨u     46ptcà48.Ë`ÜR0)ð
Ì@ÈRt CȲXäCP%CBH@ë R¨ªê¡fè[è(tº
C· Qhúz#0   ¦ÁZ°l³`O8ÁÉð28.·Àp|îOÃàX
?§:¢0ÂFBx$  !«¤i@Ú¤¹H§È[EE1PLÊ⢡V¡6£ªQP¨>ÔUÔ(j
õMFk¢ÍÑÎèt,:.FW Ðè³èô8ú¡c1L&³³³Ó9Æa¦±X¬:Öë
År°bl1¶
{{{;}#âtp¶8_\<N+ÄU
[.....]
Share Improve this question edited Jun 4, 2014 at 14:10 BastienSander asked May 30, 2014 at 9:29 BastienSanderBastienSander 1,8385 gold badges25 silver badges56 bronze badges 23
  • What I don't understand is why? Why do you need to send it back as text instead of adding an attachment header? Do your client edit the files? (I assume you have SPA clients running in the browser.) You can use data URLs for streaming PDF if you want to display it in browser. stackoverflow.com/questions/12848616/… – inf3rno Commented Jun 2, 2014 at 10:08
  • stackoverflow.com/questions/10473932/… This is how you can force a download from the browser. If you edit your binary files from there. But adding /files/xxx?aspect=attachment as a representation with forced download is much better if you store them on the server. – inf3rno Commented Jun 2, 2014 at 10:11
  • @inf3rno I didn't precised it but the thing is I cannot use data-url since this is not the way the files are stored. – BastienSander Commented Jun 2, 2014 at 10:41
  • I actually have some headers returned but because it is a rest call proceed by angular the browser doesn't receive directly the response. – BastienSander Commented Jun 2, 2014 at 10:44
  • 2 The problem is that I need to give specific headers in the REST request as I said in the my question. It is impossible to do so with a simple HTTP request... – BastienSander Commented Jun 2, 2014 at 14:17
 |  Show 18 more comments

4 Answers 4

Reset to default 5

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 )

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.

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

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.

发布评论

评论列表(0)

  1. 暂无评论