使用curl上传多个文件 [英] Upload multiple files with curl
问题描述
如何使用 CURLFile
和 curl_setopt
在数组中上传多个文件?
How do I upload multiple files in an array using CURLFile
and curl_setopt
?
使用数据数组会引发错误(无法将数组转换为字符串),并且数据上的 http_build_query
会损坏 CURLFile
对象。
Using the data array as it would throw an error (can't convert an array to a string) and http_build_query
on the data would corrupt the CURLFile
objects.
我必须上传的数据如下:
The data I have to upload looks like that:
[
'mode' => 'combine',
'input' => 'upload',
'format' => $outputformat,
'files' => [
[0] => CURLFile object,
[1] => CURLFile object,
[x] => ...
]
]
推荐答案
PHP 5.5+具有无需使用CURLFile即可创建文件的功能: curl_file_create
。
PHP 5.5+ has a function to create files without using CURLFile: curl_file_create
.
您可以上传多个文件,如下所示:
You can upload multiple files like this:
<?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);
这将在服务器上作为文件下的数组$接收c $ c>就像有已过帐的表单一样,这是
$ _ FILES
:
This will be received on the server as an array under file
the same as if there was a posted form, this is $_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
)
这篇关于使用curl上传多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!