简体   繁体   中英

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

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]);

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

First of all, Content-Type header only makes sense when you send something (POST/PUT), but not for GET requests.

Secondly, what is your issue? Guzzle by default does not store the response body (file) somewhere, so you can work with it inside your app, like $responsesfile->getBody() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM