Display PDF stream returned from controller using jquery in new window

那年仲夏 提交于 2019-12-20 14:40:54

问题


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.


回答1:


Why don't you just use standard HTML? There's no need for Javascript here (as you created a standard <a> tag for initial trigger of action).

Something like:

<form action="/PDFfile" method="post" target="_blank">
    <input type="submit" value="Show me the file in a new tab/window!"/>
</form>

Notes:

  • be sure to set an header Content-Type: application/pdf in your Azure script, so that the browser will know it's a PDF
  • as @JamesBlond stated you may not see it if you don't have a browser's plugin to read PDF. But you'll have a nice download box, and the new tab will be closed automatically


来源:https://stackoverflow.com/questions/37310855/display-pdf-stream-returned-from-controller-using-jquery-in-new-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!