使用curl上传多个文件

bsxbgnwa  于 2022-11-13  发布在  其他
关注(0)|答案(3)|浏览(507)

如何使用CURLFilecurl_setopt上传数组中的多个文件?
使用数据数组会引发错误(无法将数组转换为字符串),并且数据上的http_build_query会损坏CURLFile对象。
我必须上传的数据如下所示:

[
    'mode' => 'combine',
    'input' => 'upload',
    'format' => $outputformat,
    'files' => [
        [0] => CURLFile object,
        [1] => CURLFile object,
        [x] => ...
    ]
]
yjghlzjz

yjghlzjz1#

PHP 5.5+有一个不使用CURLFile创建文件的函数:curl_file_create
您可以上传多个文件,如下所示:

<?php

$files = [
    '/var/file/something.txt',
    '/home/another_file.txt',
];

// Set postdata array
$postData = ['somevar' => 'hello'];

// Create array of files to post
foreach ($files as $index => $file) {
    $postData['file[' . $index . ']'] = curl_file_create(
        realpath($file),
        mime_content_type($file),
        basename($file)
    );
}

$request = curl_init('https://localhost/upload');
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_POSTFIELDS, $postData);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($request);

if ($result === false) {
    error_log(curl_error($request));
}

curl_close($request);

服务器将接收到file下的数组,就像有一个发布的表单一样,这是$_FILES

Array
(
    [file] => Array
        (
            [name] => Array
                (
                    [0] => 1.txt
                    [1] => 2.txt
                )

            [type] => Array
                (
                    [0] => text/plain
                    [1] => text/plain
                )

            [tmp_name] => Array
                (
                    [0] => /private/var/folders/cq/7262ntt15mqdmylblg9p1wf80000gn/T/phpp8SsKD
                    [1] => /private/var/folders/cq/7262ntt15mqdmylblg9p1wf80000gn/T/php73ijEP
                )

            [error] => Array
                (
                    [0] => 0
                    [1] => 0
                )

            [size] => Array
                (
                    [0] => 6
                    [1] => 6
                )

        )

)

这是$_POST

Array
(
    [somevar] => hello
)
1cosmwyk

1cosmwyk2#

索引是键的一部分

[
    'mode' => 'combine',
    'input' => 'upload',
    'format' => $outputformat,
    'files[0]' => CURLFile object,
    'files[1]' => CURLFile object,
    'files[x]' => CURLFile object
     ...
    ]
]
kgqe7b3p

kgqe7b3p3#

我知道,这是老问题,但我也面临同样的问题。我还没有找到cURL的解决方案,但能够使用file_get_contents解决问题。注意,我对所有文件使用 * 相同的密钥 *。
示例:

/* Prepare request */
$multipartBoundary = "--------------------------" . microtime(true);
$contentType = "multipart/form-data; boundary={$multipartBoundary}";
$content = "";

// Files
$paramName = "files";
foreach ($files as $file) {
    $fileBaseName = basename($file);
    $fileContent = file_get_contents($file);
    $content .= "--{$multipartBoundary}\r\n";
    $content .= "Content-Disposition: form-data; name=\"{$paramName}\"; filename=\"{$fileBaseName}\"\r\n";
    $content .= "Content-Type: application/zip\r\n\r\n{$fileContent}\r\n";
}

// Regular params
foreach ($params $key=>$value) {
    $content .= "--{$multipartBoundary}\r\n";
    $content .= "Content-Disposition: form-data; name=\"{$key}\"\r\n\r\n{$value}\r\n";
}

// End
$content .= "--{$multipartBoundary}--\r\n";

// Create context
$context = stream_context_create(['http' => [
    'header' => "Content-type: {$contentType}",
    'method'  => "POST",
    'timeout' => 5, // Seconds
    'content' => $content,
    'ignore_errors' => true // Do not report about HTTP errors as PHP Warnings
]]);


/* Send request */
$apiUrl = "https//api.example.com";
$endpoint = "/upload";
$url = $apiUrl . $endpoint;
$body = file_get_contents($url, false, $context);
$headerInfo = explode(" ", $http_response_header[0]);
$code = (int)$headerInfo[1];
$message = implode(" ", array_slice($headerInfo, 2));


/* Return result */
return [$body, $code, $message];

相关问题