anonymous
anonymous

Reputation: 101

AJAX response need to be converted to blob

I have written ajax code to set request headers in url and convert that to a blob and pass to a function showFile (blob); The blob is then processed and downloaded in pdf format The blob value obtained in the code is coming as undefined. Can someone please help me to resolve the issue`

   var resolved = function (url) {
        var showFile = function (blob) {
            var newBlob = new Blob([blob], {type:"application/pdf"})                   
            const data = window.URL.createObjectURL(newBlob);
            var link = document.createElement('a');
            link.href = data;
            link.download = options.name;
            link.click();
            setTimeout(function () {
                window.URL.revokeObjectURL(data);
            }, 100)
        }
        var jwtToken = localStorage.getItem("jwtToken");
        var headerObj = {"Authorization": "Bearer " + jwtToken}

        var xhr = new XMLHttpRequest();
        $.ajax({
            dataType:'blob',
            type:'GET',
            url:url
        }).done(function(blob){
            showFile(blob); 
        });
    };

Upvotes: 5

Views: 10057

Answers (1)

Musa
Musa

Reputation: 97672

If you need a blob response from jQuery ajax, set the responseType field of xhrFields to blob. Since the response will be a blob you don't have to create one.
Also, did you forget to add your auth header to the request?

   var resolved = function (url) {
        var showFile = function (blob) {                 
            const data = window.URL.createObjectURL(blob);
            var link = document.createElement('a');
            link.href = data;
            link.download = options.name;
            link.click();
            setTimeout(function () {
                window.URL.revokeObjectURL(data);
            }, 100)
        }
        var jwtToken = localStorage.getItem("jwtToken");
        var headerObj = {"Authorization": "Bearer " + jwtToken}

        var xhr = new XMLHttpRequest();
        $.ajax({
            xhrFields: {
               responseType: 'blob' 
            }
            headers: headerObj, 
            type:'GET',
            url:url
        }).done(function(blob){
            showFile(blob); 
        });
    };

Upvotes: 5

Related Questions