我有一个 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,调用 URL.createObjectURL()
blob 获取 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。关于如何做到这一点有什么建议吗?
最佳答案
尝试
var data = response.arraybuffer();
然后从那里创建一个 Blob with the right content type
var = new Blob(data, 'application/pdf');
关于javascript - 通过 Blob URI 在新窗口中从 PUT 获取 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46594875/