【问题标题】:Upload File in chunks to URL Endpoint using Guzzle PHP使用 Guzzle PHP 将文件分块上传到 URL 端点
【发布时间】:2017-12-24 06:12:23
【问题描述】:

我想使用 guzzle 将文件分块上传到 URL 端点。

我应该能够提供 Content-Range 和 Content-Length 标头。

使用 php 我知道我可以使用拆分

define('CHUNK_SIZE', 1024*1024); // Size (in bytes) of chunk

function readfile_chunked($filename, $retbytes = TRUE) {
    $buffer = '';
    $cnt    = 0;
    $handle = fopen($filename, 'rb');

    if ($handle === false) {
        return false;
    }

    while (!feof($handle)) {
        $buffer = fread($handle, CHUNK_SIZE);
        echo $buffer;
        ob_flush();
        flush();

        if ($retbytes) {
            $cnt += strlen($buffer);
        }
    }

    $status = fclose($handle);

    if ($retbytes && $status) {
        return $cnt; // return num. bytes delivered like readfile() does.
    }

    return $status;
}

如果可能的话,如何使用 guzzle 流来实现以块的形式发送文件?

【问题讨论】:

标签: php stream guzzle6 guzzle


【解决方案1】:

只需使用 multipart 正文类型,因为它是 described in the documentation。 cURL 然后在内部处理文件读取,您不需要自己实现分块读取。此外,所有必需的标头都将由 Guzzle 配置。

【讨论】:

    【解决方案2】:

    此方法允许您使用 guzzle 流传输大文件:

    use GuzzleHttp\Psr7;
    use GuzzleHttp\Client;
    use GuzzleHttp\Psr7\Request;
    
    $resource = fopen($pathname, 'r');
    $stream = Psr7\stream_for($resource);
    
    $client = new Client();
    $request = new Request(
            'POST',
            $api,
            [],
            new Psr7\MultipartStream(
                [
                    [
                        'name' => 'bigfile',
                        'contents' => $stream,
                    ],
                ]
            )
    );
    $response = $client->send($request);
    

    【讨论】:

      猜你喜欢
      • 2021-10-27
      • 2018-01-20
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      • 2019-01-31
      • 2017-01-08
      • 2016-05-31
      相关资源
      最近更新 更多