使用Guzzle发送未知数量的文件

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

我现在使用Guzzle将用户上传的多个文件发送到另一台服务器。

根据我的理解,我们可以使用以下代码使用Guzzle发送文件:

'multipart' => [
    [
        'name'     => 'FileContents',
        'contents' => file_get_contents($path . $name),
        'filename' => $name
    ],
    [
        'name'     => 'FileInfo',
        'contents' => json_encode($fileinfo)
    ]
],

但是,由于上传的文件数可能不同,上面的代码只能用于发送一个文件。如何使用Guzzle发送未知数量的文件?非常感谢你!

php guzzle
1个回答
0
投票

这取决于您发送请求的服务器。它能够处理FileContentsFileInfo中的数组吗?或者类似FileContents_1FileContents_2FileContents_N?这取决于您的服务器。

无论如何,在Guzzle中你可以轻松地用一个循环填充数组:

$multipart => []
foreach ($files as $file) {
    $multipart[] = [
        'name'     => 'FileContents[]',
        'contents' => fopen($path . $name, 'r'),
        'filename' => $name
    ];
    $multipart[] = [
        'name'     => 'FileInfo[]',
        'contents' => json_encode($fileinfo)
    ]
}

附:

另外最好使用fopen()而不是file_get_contents(),因为你不需要读取脚本中的文件,只是将它们传递给Guzzle。

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