Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guzzle 6 download file

Need help using Guzzle 6 for downloading a file from a rest API. I don't want the file to be saved locally but downloaded from web browser. Code so far below, but believe I am missing something?

    <?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;
    ?>
like image 733
Kevin Lindmark Avatar asked Aug 20 '19 17:08

Kevin Lindmark


2 Answers

Just do research inside Guzzle's docs, for example here

Pass a string to specify the path to a file that will store the contents of the response body:

$client->request('GET', '/stream/20', ['sink' => '/path/to/file']);

Pass a resource returned from fopen() to write the response to a PHP stream:

$resource = fopen('/path/to/file', 'w');
$client->request('GET', '/stream/20', ['sink' => $resource]);

Pass a Psr\Http\Message\StreamInterface object to stream the response body to an open PSR-7 stream.

$resource = fopen('/path/to/file', 'w');
$stream = GuzzleHttp\Psr7\stream_for($resource);
$client->request('GET', '/stream/20', ['save_to' => $stream]);
like image 57
Chris Avatar answered Nov 08 '22 15:11

Chris


stream_for is deprecated in version 7.2. You can use GuzzleHttp\Psr7\Utils::streamFor($resource) instead.

like image 42
Abdullahi Abdulkabir Avatar answered Nov 08 '22 14:11

Abdullahi Abdulkabir