【问题标题】:How to save PDF file in JS (from ajax)如何在 JS 中保存 PDF 文件(来自 ajax)
【发布时间】:2020-01-04 08:54:56
【问题描述】:

我使用 PHP 来获取它,因为我需要从另一台服务器下载 PDF 文件。要下载此文件,我需要登录,而客户端不必登录。

问题是用户得到的 PDF 文件只是一个白页。 在我的服务器上,当我将内容写入文件时,里面仍然有内容 (file_put_contents("test.pdf",$content);)

我在发送之前尝试对它进行 base64 编码,并发现交付的数据仍然正确。所以它在解码(atob(data))或下载功能中失败。 (我也试过utf8编码)

在下载的 pdf 文件中,许多字符与这些框或问号 (��) 交换。

$result = curl_exec($ch);
file_put_contents("test.pdf",$result); //test.pdf contains correct document
echo base64_encode($result);
download(atob(data),"My.pdf") //data is answer of ajax request

function download(data, filename, type) {
    var file = new Blob([data], {
        type: type
    });
    if (window.navigator.msSaveOrOpenBlob) // IE10+
        window.navigator.msSaveOrOpenBlob(file, filename);
    else { // Others
        var a = document.createElement("a"),
            url = URL.createObjectURL(file);
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        setTimeout(function () {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        }, 0);
    }
}

【问题讨论】:

    标签: javascript php pdf download php-curl


    【解决方案1】:

    要显示 pdf(或任何其他文件类型),您必须在响应标头中设置内容类型等,以便浏览器正确解析并显示。这是我为向用户提供 pdf 内容而编写的代码的一小部分。

      $file = '/home/public_html/DriveMode/DRIVES/java.pdf'; //path to file
      $filename = 'filename.pdf';
      header('Content-type: application/pdf'); //setting content type in header
      header('Content-Disposition: inline; filename="' . $filename . '"');
      header('Content-Transfer-Encoding: binary');
      header('Accept-Ranges: bytes'); 
      readfile($file); // reads and writes the file to output buffer
    

    希望这对您有所帮助,如果这里有什么令人困惑的地方,请在 cmets 中告诉我。

    【讨论】:

    • 这不是在回答我的问题。这只是一个普通的pdf文件下载。
    • 我不知道$result 中存储了什么,但是当您使用file_put_contents("test.pdf",$result); 时,您实际上是在将$result 的内容写入文件test.pdf,并且您希望提供结果file。所以从技术上讲,您应该回显test.pdf 而不是$result,为此,您需要像我所做的那样在response header 中设置content type as pdf 等等。
    • test.pdf 正如名称和描述所说,只是一个测试。当有多个用户时,我也不能使用这个文件。 $result 是整个 test.pdf,所以我可以使用 '$result' 并且声明我不想在某处显示 pdf,只需通过 xhr 将其发送到 js 并保存,所以我不需要这个标题。
    【解决方案2】:

    问题在于 BLOB 构造函数中的隐式 UTF8 编码。 更多信息here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-10
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 2019-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多