Using Javascript to add custom http header and trigger file download

后端 未结 3 1839
你的背包
你的背包 2021-01-11 14:19

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/s         


        
相关标签:
3条回答
  • 2021-01-11 15:10

    https://stackoverflow.com/a/12372670/1961561 could be a solution for your problem.

    $.ajax({
      url: "/test",
      headers: {"X-Test-Header": "test-value"}
    });
    
    0 讨论(0)
  • 2021-01-11 15:20

    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.

    0 讨论(0)
  • 2021-01-11 15:20

    It is not possible to add custom http header when you download a file by clicking on a link.

    However, in your use case, you might store the token in a cookie, which will be automatically added to all browser requests.

    0 讨论(0)
提交回复
热议问题