【问题标题】:Laravel - How to save binary from GuzzleLaravel - 如何从 Guzzle 中保存二进制文件
【发布时间】:2019-11-30 19:57:41
【问题描述】:

我需要帮助,我使用以下代码请求文件:

$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

我的问题是:如何存储这个文件?我在互联网上找不到任何东西...

【问题讨论】:

    标签: php laravel guzzle


    【解决方案1】:

    使用Storage facade 创建一个新文件。

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

    如果 Mime Type 可以更改,则获取文件,然后使用 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)
    ]);
    

    【讨论】:

    • 当你说“没有工作”时,你收到了什么错误?您尝试了哪些步骤来解决它?
    • 没有收到任何错误,它保存了“文件”但没有内容,我现在不在电脑旁,但过几分钟我会试试这个:stackoverflow.com/questions/36771849/…
    • 该问题旨在通过浏览器将文件作为下载流传输给用户。 Laravel 对此有内置的功能。您最初的问题是关于将文件从网络下载到您的服务器。
    • 添加了另外两种获取文件的方法。
    • 有什么想法@CaioKawasaki 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    相关资源
    最近更新 更多