3

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...

Caio Kawasaki
  • 2,894
  • 6
  • 33
  • 69

1 Answers1

4

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)
]);
lufc
  • 1,965
  • 2
  • 15
  • 19
  • 1
    When you say "didn't work", what error did you receive? And what steps did you try to resolve it? – lufc Jul 22 '19 at 20:16
  • didn’t get any error, it saves “the file” but it has no content, I am away from my computer right now, but in some minutes I’ll try this: https://stackoverflow.com/questions/36771849/guzzle-get-file-and-forward-it – Caio Kawasaki Jul 22 '19 at 20:17
  • That question is designed to stream the file to a user as a download via their browser. Laravel has built-in features for this. Your original question was about downloading a file from the web to your server. – lufc Jul 22 '19 at 20:24
  • Have added two more methods to get the file with. – lufc Jul 22 '19 at 20:40
  • Any thoughts @CaioKawasaki ? – lufc Jul 24 '19 at 00:42