Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display PDF stream returned from controller using jquery in new window

I have a controller action which reads a .pdf file from azure blobstorage and returns stream object to the $.ajax() method.

Controller returns

var stream = blobStorage.OpenRead(filepath);
await FileAsync(stream, "application/pdf");

Ajax call and response

$.ajax({
        type: "POST",
        url: "/PDFfile",
        data: { 'id': Id },
        dataType: "application/pdf",
        traditional: true,
        complete: function(data) {
            var w = window.open("data:application/pdf, " + escape(data.responseText));
            w.document.write(data.responseText);
            w.document.close();
        }
    });

However, if the call is to the same controller action as shown, the file is displayed correctly.

<a class="pull-right btn-link" target="_blank" data-bind="attr: { href: '/PDFfile/' + Id }"></a>

It may appear as a duplicate question but none of the solutions worked for me. The output I am getting is as shown.enter image description here

like image 782
user3469799 Avatar asked May 18 '16 22:05

user3469799


1 Answers

I couldnt find a exact answer to this question. I found a bunch of different questions. I finally was able to piece together by using fetch. You need to accept type 'arraybuffer', then you turn into a blob with resopnse.blob(). Then you can open the blob in a new window.

          fetch('/post/url', {
                        method: 'POST',
                        headers: {
                            Accept: 'arraybuffer',
                            'Content-Type': 'application/json',
                        },
                        //you need to use json here
                        body: JSON.stringify({ items: [{ ItemId: 3, Quantity: 40 }], fileId: 2 });
                    })
                        .then(response => response.blob())
                        .then(data => {
                            var popup = window.open(URL.createObjectURL(data), "height=500,width=750);

                   });
like image 168
barryDev Avatar answered Nov 14 '22 20:11

barryDev