cURL上传到Google云端硬盘

时间:2012-11-20 23:13:59

标签: php curl upload google-drive-api

我可以通过json在Google云端硬盘中创建一个文件进入云端硬盘文件夹:

$data = array(
    "title" => $_FILES['file']['name'],
    "parents" => array(array(
        "kind" => "drive#parentReference",
        "id" => $parent_id
    )),
    "mimeType" => "application/pdf"
);
$data = json_encode($data);

$url = "https://www.googleapis.com/drive/v2/files?oauth_token=".$accessToken;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

但我无法找到在其上添加PDF文件的方法,因为在Google云端硬盘文档中未指定json属性。

我必须在哪里添加文件内容? 这可能吗?

我是否必须将文件上传到上传/驱动器,然后上传带有文件夹ID的元数据?我没有意识到这一点。

1 个答案:

答案 0 :(得分:2)

您希望将文件放在正文中(即在CURLOPT_POSTFIELDS中)。您还需要指定与文件类型和Content-Length匹配的Content-Type。

这是well documented

文件元数据应该转到/ drive / v2 / files,而不是/ upload / drive / v2 / files。

这样,您必须提出两个请求。

如果要同时同时执行文件和元数据,可以使用API​​和文件插入:

https://developers.google.com/drive/v2/reference/files/insert

请注意,PHP library可以让您更轻松。

相关问题