Guzzle 6 下载文件
Guzzle 6 download file
需要帮助使用 Guzzle 6 从 rest 下载文件 API。我不希望文件保存在本地而是从网络浏览器下载。到目前为止的代码,但相信我遗漏了什么?
<?php
//code for Guzzle etc removed
$responsesfile = $client->request('GET', 'documents/1234/content',
[
'headers' => [
'Cache-Control' => 'no-cache',
'Content-Type' => 'application/pdf',
'Content-Type' => 'Content-Disposition: attachment; filename="test"'
]
]
);
return $responsesfile;
?>
首先,Content-Type
header 仅在发送内容时才有意义 (POST/PUT),但对 GET 请求无效。
其次,你的问题是什么? Guzzle 默认情况下不会将响应 body (文件)存储在某处,因此您可以在应用程序中使用它,例如 $responsesfile->getBody()
.
只需在 Guzzle 的文档中进行研究,例如 here
传递一个字符串以指定将存储响应正文内容的文件的路径:
$client->request('GET', '/stream/20', ['sink' => '/path/to/file']);
传递从 fopen() 返回的资源以将响应写入 PHP 流:
$resource = fopen('/path/to/file', 'w');
$client->request('GET', '/stream/20', ['sink' => $resource]);
传递 Psr\Http\Message\StreamInterface 对象以将响应主体流式传输到打开的 PSR-7 流。
$resource = fopen('/path/to/file', 'w');
$stream = GuzzleHttp\Psr7\stream_for($resource);
$client->request('GET', '/stream/20', ['save_to' => $stream]);
stream_for
在 7.2 版中已弃用。您可以使用
GuzzleHttp\Psr7\Utils::streamFor($resource)
相反。
需要帮助使用 Guzzle 6 从 rest 下载文件 API。我不希望文件保存在本地而是从网络浏览器下载。到目前为止的代码,但相信我遗漏了什么?
<?php
//code for Guzzle etc removed
$responsesfile = $client->request('GET', 'documents/1234/content',
[
'headers' => [
'Cache-Control' => 'no-cache',
'Content-Type' => 'application/pdf',
'Content-Type' => 'Content-Disposition: attachment; filename="test"'
]
]
);
return $responsesfile;
?>
首先,Content-Type
header 仅在发送内容时才有意义 (POST/PUT),但对 GET 请求无效。
其次,你的问题是什么? Guzzle 默认情况下不会将响应 body (文件)存储在某处,因此您可以在应用程序中使用它,例如 $responsesfile->getBody()
.
只需在 Guzzle 的文档中进行研究,例如 here
传递一个字符串以指定将存储响应正文内容的文件的路径:
$client->request('GET', '/stream/20', ['sink' => '/path/to/file']);
传递从 fopen() 返回的资源以将响应写入 PHP 流:
$resource = fopen('/path/to/file', 'w');
$client->request('GET', '/stream/20', ['sink' => $resource]);
传递 Psr\Http\Message\StreamInterface 对象以将响应主体流式传输到打开的 PSR-7 流。
$resource = fopen('/path/to/file', 'w');
$stream = GuzzleHttp\Psr7\stream_for($resource);
$client->request('GET', '/stream/20', ['save_to' => $stream]);
stream_for
在 7.2 版中已弃用。您可以使用
GuzzleHttp\Psr7\Utils::streamFor($resource)
相反。