【问题标题】:Download file using wp_remote_post request from API使用来自 API 的 wp_remote_post 请求下载文件
【发布时间】:2018-10-20 14:21:14
【问题描述】:

我正在根据给定的参数和详细信息向端点发出 API 请求,它将以 PDF 格式发回一份报告,供我查看我发送给它的详细信息。我正在使用 wp_remote_post 的 WordPress,但无法将文件下载到计算机。

关于downloading a file in PHP via REST 的这个问题很有帮助,但不能完全处理相同类型的事情/场景,所以我一直坚持如何让它按照我的需要工作。

这是我使用 PHP var_dump 得到的回复:

'date' => string 'Thu, 10 May 2018 11:25:00 GMT' (length=29)
'server' => string 'Apache/2.4.7 (Ubuntu)' (length=21)
'content-disposition' => string 'attachment; filename="xyz.pdf"' (length=37)
'cache-control' => string 'no-cache, private' (length=17)
'x-ratelimit-limit' => string '60' (length=2)
'x-ratelimit-remaining' => string '58' (length=2)
'content-type' => string 'application/pdf' (length=15)

在响应的正文部分,我得到了这个:

  'body' => string '%PDF-1.4
1 0 obj
<<
/Title ( title )
/Creator ( creator )
/Producer ( producer )
/CreationDate ( creationdate )
'... (length=22237)

我从回复中相信 wkhtmltopdf 是创建正在发回的 PDF 的库/框架。如何将此文件以 PDF 文件的形式下载到计算机上并提供给请求它的用户?

我尝试过回复回复并使用urldecode,但我不确定这是什么回复以及如何处理。

【问题讨论】:

    标签: php wordpress rest


    【解决方案1】:

    您可能只需要设置正确的响应标头。您可以使用“wp_remote_retrieve_body”获取响应正文,设置标题并回显 PDF 数据。下面是一个例子:

    $data = wp_remote_retrieve_body($response);
    header('Content-type: application/pdf');
    header('Content-Disposition: attachment; filename="somefile.pdf"');
    echo $data;
    

    这应该会导致文件自动下载。如果您希望文件显示在浏览器窗口中,请使用“内联”作为 Content-Disposition 标头。

    header('Content-Disposition: inline');
    

    【讨论】:

    • 我已经添加了您在上面发布的代码,但我似乎收到了 ERR_INVALID_RESPONSE 错误。
    • This other answer 帮助修复了无效响应,我需要将这两个参数添加到 header 函数中。但是,谢谢,因为这肯定让我走上了正确的道路。非常感谢。
    猜你喜欢
    • 2015-10-27
    • 2020-09-08
    • 1970-01-01
    • 2021-08-06
    • 2014-01-16
    相关资源
    最近更新 更多