【问题标题】:PDF from PUT in new window via Blob URI通过 Blob URI 在新窗口中 PUT 中的 PDF
【发布时间】:2018-03-17 14:51:10
【问题描述】:

我有一个 API 端点,它在 PUT 上提供带有 Content-Type "application/pdf" 的 PDF(您可能会问“为什么是 PUT 而不是 GET?”,答案是“它很复杂,我无法更改它” )。

我想(客户端)请求该 PDF 并在window.open() 调用中显示结果(即在新窗口中显示 PDF)。以前我使用数据 URI 来执行此操作,即:

window.open('data:application/pdf,<the data payload from the response>');

但在 Chrome 60 中,这不再有效(您不能在 window.open 中使用数据 URI,请参阅 https://bugs.chromium.org/p/chromium/issues/detail?id=751135)。

我现在已更改客户端代码以执行同一端点的fetch(),从响应中创建一个 blob,在 blob 上调用 URL.createObjectURL() 以获取一个 url,并将该 url 传递给 window.open()称呼。即我有类似的东西:

fetch('http://somedomain.com/rest/getMyPdf', {
    method: 'PUT', 
    ... some headers & the body ...
}).then(function(response) {
    return response.blob();
}).then(function(blob) {
    window.open(URL.createObjectURL(blob));
});

这在 Firefox 中有效(我在新窗口中获得了 PDF),但在 Chrome 中您只能看到 PDF 内容的原始 ASCII(即%PDF-1.3.....)。

我猜这是某种内容类型问题,即如果我可以在 url 上设置内容类型,那么 Chrome 会将响应解释为 PDF。关于如何做到这一点的任何建议?

【问题讨论】:

  • 谢谢!是的,它做到了(虽然不需要Uint8Array,只是来自arrayBuffer 的原始结果)。想要充实它并添加作为答案,我会接受吗?

标签: javascript google-chrome pdf


【解决方案1】:

试试

var data = response.arraybuffer();

然后从那里创建一个 Blob with the right content type

var = new Blob(data, 'application/pdf');

【讨论】:

    猜你喜欢
    • 2020-11-08
    • 2017-05-21
    • 2016-03-30
    • 2017-06-12
    • 2014-07-01
    • 1970-01-01
    • 2013-04-06
    • 2013-03-07
    • 2013-12-22
    相关资源
    最近更新 更多