Request a file with a custom header

后端 未结 2 2017
故里飘歌
故里飘歌 2020-12-05 08:23

I have an unusual requirement. Essentially I need a way so that, when the user clicks on a link or button, they will receive a PDF. The tricky part here is that the server w

2条回答
  •  醉梦人生
    2020-12-05 08:43

    Tested to work in chrome:

    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", "/test.pdf" ); //I had test.pdf this on my local server
    
    
    xhr.addEventListener( "load", function(){
        var data = toBinaryString(this.responseText);
        data = "data:application/pdf;base64,"+btoa(data);
        document.location = data;
    }, false);
    
    xhr.setRequestHeader("magic", "header" );
    xhr.overrideMimeType( "application/octet-stream; charset=x-user-defined;" );
    xhr.send(null);
    

    You can change application/pdf to application/octet-stream to have download prompt. But it's pretty easy to download from the chrome's reader as well.

    In firefox nothing happens I guess it's because I don't have a plugin to deal with application/pdf installed. Changing to application/octet-stream will prompt a dl.

    With IE I suppose you need some kind of VBScript/ActiveX hackery

    If the file is huge, using data uri might crash the browser, in that case you can use BlobBuilder and Object URLs.

提交回复
热议问题