Laravel - 如何从 Guzzle 保存二进制文件
Laravel - How to save binary from Guzzle
我需要帮助,我使用以下代码请求文件:
$client = new Client(['verify' => false]);
$response = $client->request('GET', 'https://url', [
'headers' => [
'Authorization' => 'Bearer token'
]
]);
$mime = $response->getHeader('Content-Type');
$binary = $response->getBody();
我收到的答案如下:
Content-Type: image/jpeg or other appropriate media type
Content-Length: content-size
binary-media-data
我的问题是:如何存储这个文件?我在互联网上找不到任何东西...
使用 Storage facade 创建一个新文件。
Storage::put('file.jpg', $binary)
如果 Mime 类型可以更改,则获取文件,然后使用 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));
如果文件名始终可靠并且您不担心重复,那么您可以使用 Guzzle 直接输入:
$client = new Client(['verify' => false]);
$filePath = basename($url);
$response = $client->request('GET', $url, [
'headers' => [
'Authorization' => 'Bearer token'
],
'sink' => storage_path('dir_within_storage/'.$filePath)
]);
我需要帮助,我使用以下代码请求文件:
$client = new Client(['verify' => false]);
$response = $client->request('GET', 'https://url', [
'headers' => [
'Authorization' => 'Bearer token'
]
]);
$mime = $response->getHeader('Content-Type');
$binary = $response->getBody();
我收到的答案如下:
Content-Type: image/jpeg or other appropriate media type
Content-Length: content-size
binary-media-data
我的问题是:如何存储这个文件?我在互联网上找不到任何东西...
使用 Storage facade 创建一个新文件。
Storage::put('file.jpg', $binary)
如果 Mime 类型可以更改,则获取文件,然后使用 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));
如果文件名始终可靠并且您不担心重复,那么您可以使用 Guzzle 直接输入:
$client = new Client(['verify' => false]);
$filePath = basename($url);
$response = $client->request('GET', $url, [
'headers' => [
'Authorization' => 'Bearer token'
],
'sink' => storage_path('dir_within_storage/'.$filePath)
]);