Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - How to save binary from Guzzle

I need help, I make the request for a file using the following code:

$client = new Client(['verify' => false]);

$response = $client->request('GET', 'https://url', [
    'headers' => [
        'Authorization' => 'Bearer token'
    ]
]);

$mime = $response->getHeader('Content-Type');
$binary = $response->getBody();

The answer I receive is the following:

Content-Type: image/jpeg or other appropriate media type
Content-Length: content-size

binary-media-data

My question is: How to store this file? I could not find anything on the internet...

like image 961
Caio Kawasaki Avatar asked Oct 30 '25 04:10

Caio Kawasaki


1 Answers

Use the Storage facade to create a new file.

Storage::put('file.jpg', $binary)

If the Mime Type can change then get the file and then use PutFile:

use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;

$client = new Client(['verify' => false]);

$tmpfile = tempnam(sys_get_temp_dir(),'dl');

$response = $client->request('GET', $url, [
    'headers' => [
        'Authorization' => 'Bearer token'
    ],
    'sink' => $tmpfile
]);

$filename = Storage::putFile('dir_within_storage', new File($tmpfile));

If the file name is always reliable and you're not worried about duplicates then you can just uze Guzzle to put it directly:

$client = new Client(['verify' => false]);

$filePath = basename($url);

$response = $client->request('GET', $url, [
    'headers' => [
        'Authorization' => 'Bearer token'
    ],
    'sink' => storage_path('dir_within_storage/'.$filePath)
]);
like image 132
lufc Avatar answered Nov 01 '25 19:11

lufc