【发布时间】:2020-07-02 23:03:25
【问题描述】:
将文件上传到 GoogleDrive 后,我可以从响应中获取 fileId,然后将 fileId 传递给以下函数:
public function createShareLink($fileId, $accessToken){
$ch = curl_init();
$options = [
CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files/'.$fileId.'/permissions',
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode(['type'=>'anyone', 'role'=>'reader',]),
CURLOPT_HTTPHEADER => [
'Authorization:Bearer '.$accessToken,
'Content-Type:application/json',
],
//In case you're in Windows, sometimes will throw error if not set SSL verification to false
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
];
//In case you need a proxy
//$options[CURLOPT_PROXY] = 'http://127.0.0.1:1087';
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
return $result;
}
它确实有效,它返回一个 json:
{
"kind": "drive#permission",
"id": "anyoneWithLink",
"type": "anyone",
"role": "reader",
"allowFileDiscovery": false
}
但是响应json中没有分享链接,所以我查看了文档,在here,你可以找到fields参数(见下面的截图):
单击partial response 会将您重定向到一个页面,其中包含一些有关如何将值传递给fileds 参数的示例。
我按照示例将webViewLink 作为值传递给fields,如下所示:
CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files/'.$fileId.'/permissions?fields=webViewLink',
但是响应一个错误:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalidParameter",
"message": "Invalid field selection webViewLink",
"locationType": "parameter",
"location": "fields"
}
],
"code": 400,
"message": "Invalid field selection webViewLink"
}
}
我试过id:
CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files/'.$fileId.'/permissions?fields=id',
回复是:
{
"id": "anyoneWithLink"
}
我试过name:
CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files/'.$fileId.'/permissions?fields=name',
回复是:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalidParameter",
"message": "Invalid field selection name",
"locationType": "parameter",
"location": "fields"
}
],
"code": 400,
"message": "Invalid field selection name"
}
}
我试过mimeType:
CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files/'.$fileId.'/permissions?fields=mimeType',
回复是:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalidParameter",
"message": "Invalid field selection mimeType",
"locationType": "parameter",
"location": "fields"
}
],
"code": 400,
"message": "Invalid field selection mimeType"
}
}
我真的不知道这个fields 参数如何工作,因为我认为webViewLink、name 和mimeType 是正确的字段,它们都在here 中描述,任何人都这样做了之前?我不会使用google-api-php-client,因为它的大小太大(>20M)。
【问题讨论】:
-
使用 google 提供的 api 始终是一个不错的选择,RAW api 确实有效,但从编码和异常处理的角度来看都需要付出很多努力。我不确定为什么大于 20M 的大小对您来说是个问题,因为现在存储并不重要,除非您在物联网设备上运行服务器。
-
@SariqShaikh 其实这不是关于存储,而是关于
google-api-php-client占用了我工具大小的 1/3(我正在开发一个上传工具),因为图书馆有很多问题,例如this one,并且它缺乏文档,就像我真的不知道如何使用google-api-php-client 上传多个块中的文件,有时文档没有php示例,例如@ 987654328@,但我用 GuzzleHttp 解决了所有问题。
标签: google-drive-api google-api-php-client php-curl