Safari 12 Won't Download a PDF blob

♀尐吖头ヾ 提交于 2019-12-01 17:42:23

Apparently this is a Safari 12 bug that sometimes happens. It's not fixed by target = "_self", which pertains to a different regression bug.

Until the bug is fixed, the ugly workaround is:

  1. Send the blob to the server which saves the file remotely.
  2. Download the remote file.

Javascript Code

   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 Code

In 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);
?>

In 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");
?>
Bertrand Steenput

It seems that it is the target = "_blank" that is not working. I have replaced it with _self, which apparently solved the problem. I found this when I had the same issue.

If someone has a idea on why we cannot use _blank I would love to hear that.

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