转换cURL以在php函数中使用

时间:2016-12-16 08:06:34

标签: php curl box-api box

目前正在使用box平台,并尝试将文件上传到盒式服务器。 Box使用cURL上传文件,我试图从php发送cURl请求。到目前为止,我已经将大部分cURL commads转换为php术语,但我无法弄清楚如何传递要上传的文件的属性(名称,路径,包含文件夹)。

这是cURL

curl https://upload.box.com/api/2.0/files/content -H "Authorization: Bearer APP_USER_TOKEN" -X POST -F attributes='{"name":"Jon_Snow.jpeg", "parent":{"id":"0"}}' -F file=@Jon_Snow.jpeg

这里是不完整的cURL命令的php版本。

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://upload.box.com/api/2.0/files/content");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = "Authorization: Bearer ".json_decode($accessToken, true )['access_token'];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);

如何执行cURL命令的最后一部分

-F attributes='{"name":"Jon_Snow.jpeg", "parent":{"id":"0"}}' -F file=@Jon_Snow.jpeg

编辑:可能重复的建议'是不准确的,我想问一种方法,以-F attributes='{"name":"Jon_Snow.jpeg", "parent":{"id":"0"}}'的形式向上传的文件添加属性我不知道建议的答案是如何相关的

2 个答案:

答案 0 :(得分:1)

找到答案,我需要json_encode属性数组,然后使用new \CURLFile()函数创建文件句柄,它不适用于realpath()

$attributes = array('name'=>$fileName,'parent'=>array('id'=>$folderId));
$file = new \CURLFile($filePath);
$fields = array('attributes' => json_encode($attributes), 'file' => $file);
$headers = array("Authorization: Bearer ".$accessToken);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uploadUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

$result = curl_exec($ch);

答案 1 :(得分:-1)

试试这个:art about sending files via post and curlib

-F选项表示您发送包含姓名和内容的帖子字段。在这种情况下,内容来自文件,因为您正在使用@前缀