使用Guzzle PHP将文件大块上传到URL端点

问题描述 投票:1回答:2

我想使用食人鱼将文件大块上传到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(如果可能)使用guzzle流按块发送文件?

php stream guzzle guzzle6 guzzlehttp
2个回答
3
投票

这种方法允许您使用大量流传输大型文件:

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);

1
投票

只需使用文档中所述的 multipart主体类型即可。 然后,cURL在内部处理文件读取,您不需要自己实现分块读取。 同样,所有必需的标头也将由Guzzle配置。

© www.soinside.com 2019 - 2024. All rights reserved.