【问题标题】:Can't save blob url pdf from safari 12.1 on mac无法从 Mac 上的 safari 12.1 保存 blob url pdf
【发布时间】:2019-09-04 01:27:01
【问题描述】:
我将 iframe src 设置为格式为“blob:http://localhost:3000/f87808a3-9a74-4d61-b7ae-7ac37ff38325”的 blob url。 iframe 显示一个用一些 javascript 创建的 pdf。显示 pdf 在所有浏览器中都按预期工作。在 Chrome 和 Firefox 中,可以将此 pdf 下载到硬盘驱动器,浏览器集成了 pdf 查看器。
但是在 mac 上的 Safari 12.1 中,单击 pdf 查看器的下载按钮时没有任何反应。
这是 Safari 中的已知错误吗?
有没有办法让 pdf blob url 下载在 Safari 中工作?
【问题讨论】:
标签:
javascript
html
safari
【解决方案1】:
这和我的回答here有关。
显然这是Safari 12.1 bug,有时会发生。 target = "_self" 没有修复它,它属于 different regression bug。
在修复错误之前,丑陋的解决方法是:
- 将 blob 发送到远程保存文件的服务器。
- 下载远程文件。
Javascript 代码
async createDownloadElementAndClick(blob, fileName) {
let options = {
method:"POST",
body:blob
};
await fetch(`https://example.com/upload.php`, options);
window.open(`https://example.com/download.php?${fileName}`, "_self");
}
PHP 代码
在upload.php中:
<?php
// add any authentication code as necessary here
// gets entire POST body
$data = file_get_contents('php://input');
$filename = "temp/download.pdf";
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $data);
fclose($fp);
?>
在download.php中:
<?php
ob_start();
$file = $_SERVER["QUERY_STRING"];
// This is the line that tells Safari to download the file instead of opening it
header("Content-disposition: attachment; filename=$file");
header("Content-type: application/pdf", false);
readfile("temp/download.pdf");
ob_flush();
// This deletes the pdf so there is little chance of contaminating the next call
unlink("temp/download.pdf");
?>