[英]Uploading files to my Google Drive account using PHP
我知道有数百篇文章涉及该主题的变体,而我已经花了最后几个小时阅读它们,但是我无法使它正常工作。
我想通过Google Drive SDK使用PHP从服务器将文件上传到我的Google Drive帐户(我正在使用v2.2.0)。
该脚本执行正常,似乎正在某个地方上传,甚至返回了一个文件ID(尽管始终相同),但是它没有显示在我的Google云端硬盘中,当我尝试查看该文件时会收到以下消息:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "notFound",
"message": "File not found: <FILE_ID>.",
"locationType": "parameter",
"location": "fileId"
}
],
"code": 404,
"message": "File not found: <FILE_ID>."
}
}
我已经设置了一个服务帐户并下载了JSON凭证。 我的目的是创建一个用于上传存储在服务器上的文件的功能,因此不需要oAuth同意屏幕。
到目前为止,这是测试代码:
<?php
include_once __DIR__ . '/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=../../../keys/MyProject-xxxxxxxxxxxx.json');
$client = new Google_Client();
$client->addScope(Google_Service_Drive::DRIVE);
$client->useApplicationDefaultCredentials();
$client->setApplicationName("MyApplication");
$client->setScopes(['https://www.googleapis.com/auth/drive.file']);
$file = new Google_Service_Drive_DriveFile();
$file->setName(uniqid().'.jpg');
$file->setDescription('A test document');
$file->setMimeType('image/jpeg');
$data = file_get_contents('cat.jpg');
$service = new Google_Service_Drive($client);
$createdFile = $service->files->create($file, array(
'data' => $data,
'mimeType' => 'image/jpeg',
'uploadType' => 'multipart'));
echo("<a href='https://www.googleapis.com/drive/v3/files/".$createdFile->id."?key=<MY_API_KEY>&alt=media' target='_blank'>Download</a>");
解决了!
您需要在Google云端硬盘中创建一个文件夹,然后将服务帐户的电子邮件地址添加到可以添加和编辑的人员列表中。
然后,您需要在代码中指定文件夹ID:
$file->setParents(array("0B_xxxxxxxxxxxxxxxxxxxxxxxxx"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.