问题
Currently im working on box platform, and trying to upload a file to the box server. Box uses cURL to upload files, and i'm trying to send cURl requests from php. So far i've converted most of the cURL commads to php jargon, but i could't figure out how to pass in the attributes(name, path, containing folder) of the file to be uploaded.
here is the 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
and here is the php version for the incomplete cURL command.
$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);
How do i do the last part of the cURL command which is
-F attributes='{"name":"Jon_Snow.jpeg", "parent":{"id":"0"}}' -F file=@Jon_Snow.jpeg
Edit: the suggestion of 'possible duplicate' is not accurate, i am asking of a way to add attributes to the uploaded files in the form -F attributes='{"name":"Jon_Snow.jpeg", "parent":{"id":"0"}}'
i dont see how the suggested answer is relevant
回答1:
Found the answer, i needed to json_encode
the attributes array and then use new \CURLFile()
function to create a file handle, it did NOT work with 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);
回答2:
Try this: art about sending files via post and curlib
-F option means you're sending a post Field with name and content. Content in this case is from File becasue you're using @ prefix
来源:https://stackoverflow.com/questions/41179847/convert-curl-to-be-used-in-php-function