Download Binary Data as a File Via Javascript

后端 未结 1 685
孤城傲影
孤城傲影 2020-12-14 05:03

I\'m making an ajax call to an API that returns binary data. I\'m wondering if its possible to take that binary data and display it for the client in a new window? This is w

相关标签:
1条回答
  • 2020-12-14 05:15

    Okay, I figured it out. I had to specify the responseType as 'array buffer':

    function downloadPDF() {
    
        var xhr = new XMLHttpRequest();
        xhr.open('POST', API_URL, true);
        xhr.responseType = 'arraybuffer';
    
        xhr.onload = function(e) {
            if (this.status == 200) {
                var bb = new window.WebKitBlobBuilder();
                bb.append(this.response); // Note: not xhr.responseText
    
                var blob = bb.getBlob('application/pdf');
                var blobURL = window.webkitURL.createObjectURL(blob);
    
                window.open(blobURL);
            }
        };
    
        xhr.send(createRequest());
    }
    
    0 讨论(0)
提交回复
热议问题