Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Javascript to add custom http header and trigger file download

I would like to start a simple file download through the browser, however an access token must be passed with a custom HTTP header:

GET https://my.site.com/some/file
Authorization: access_token

How can I inject the Authorization: header following the site URL? I know it's possible to do that using query string, but I want to do it using headers.

I'm familiar with XMLHttpRequest, but as far as I understand it does not trigger download, it only reads content and the file I want to download is few hundred MBs at least.

xhr.setRequestHeader('Authorization', 'access_token');

This looks like a simple task, but I'm inexperienced coder so any help would be nice. Thanks.

like image 725
user2370553 Avatar asked May 16 '13 16:05

user2370553


1 Answers

I think this solves your problem:

function toBinaryString(data) {
    var ret = [];
    var len = data.length;
    var byte;
    for (var i = 0; i < len; i++) { 
        byte=( data.charCodeAt(i) & 0xFF )>>> 0;
        ret.push( String.fromCharCode(byte) );
    }

    return ret.join('');
}


var xhr = new XMLHttpRequest;

xhr.open( "GET", "https://my.site.com/some/file" );     

xhr.addEventListener( "load", function(){
    var data = toBinaryString(this.responseText);
    data = "data:application/text;base64,"+btoa(data);
    document.location = data;
}, false);

xhr.setRequestHeader("Authorization", "access_token" );
xhr.overrideMimeType( "application/octet-stream; charset=x-user-defined;" );
xhr.send(null);

Modified answer https://stackoverflow.com/a/10518190/2767026 to fit your needs.

like image 196
William Weckl Avatar answered Oct 31 '22 22:10

William Weckl