简体   繁体   中英

Download File With Guzzle

I'm attempting to retrieve a file attachment with Guzzle. The file isn't available directly through an endpoint, but the download is initiated via the end point and downloaded to my browser. Can I retrieve this file with Guzzle?

I successfully login to the site, but what is saved to my file is the html of the site not the download. The file contents seems to come through when I make the request with insomnia rest client, but not with Guzzle.

$client = new GuzzleHttp\Client();
$cookieJar = new \GuzzleHttp\Cookie\CookieJar();

$response = $client->post('https://test.com/login', [
    'form_params' => [
        'username' => $username,
        'password' => $password,
        'action' => 'login'
    ],
    'cookies' => $cookieJar
]);

$resource = fopen(__DIR__.'/../../feeds/test.xls', 'w');
$stream = GuzzleHttp\Psr7\stream_for($resource);
$response = $client->request('GET', 'https://test.com/download', ['sink' => $stream]);

If you want to perform an authentication step and then a download step, you'll need to make sure the cookies are persisted across both requests. Right now you're only passing your $cookieJar variable to the first one.

The explicit way of doing this would be to add it to the options for the second request:

['sink' => $stream, 'cookies' => $cookieJar]

but it might be easier to take advantage of the option in the client constructor itself:

$client = new GuzzleHttp\Client(['cookies' => true);

That means that every request (with that client) will automatically use a shared cookie jar, and you don't need to worry about passing it into each request separately.

You should send Content-Disposition header in order to specify that the client should receive file downloading as a response. According to your GET HTTP request which will capture the contents into the $stream resource, finally you can output these contents to browser with stream_get_contents .

<?php 

// your 3rd party end-point authentication

...

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="test.xls"'); 

$resource = fopen(__DIR__.'/../../feeds/test.xls', 'w');
$stream = GuzzleHttp\Psr7\stream_for($resource);
$response = $client->request('GET', 'https://test.com/download', ['sink' => $stream]);

echo stream_get_contents($stream);

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