简体   繁体   English

使用PHP将文件上传到我的Google云端硬盘帐户

[英]Uploading files to my Google Drive account using PHP

I'm aware that there are hundreds of posts covering variations of this topic, and I've spent the last few hours reading through them, but I just can't get this to work. 我知道有数百篇文章涉及该主题的变体,而我已经花了最后几个小时阅读它们,但是我无法使它正常工作。

I'm wanting to upload files to my Google Drive account from my server using PHP via the Google Drive SDK (I'm using v2.2.0). 我想通过Google Drive SDK使用PHP从服务器将文件上传到我的Google Drive帐户(我正在使用v2.2.0)。

The script executes fine, it seems to be uploading somewhere and even returns a file id (always the same one though), but it's not showing in my Google Drive and I get the following message when I try and view the file: 该脚本执行正常,似乎正在某个地方上传,甚至返回了一个文件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>."
 }
}

I've setup a service account and downloaded the JSON credentials. 我已经设置了一个服务帐户并下载了JSON凭证。 My aim is to create a function for uploading files stored on my server, so I don't require an oAuth consent screen. 我的目的是创建一个用于上传存储在服务器上的文件的功能,因此不需要oAuth同意屏幕。

Here's the test code so far: 到目前为止,这是测试代码:

<?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>");

Solved! 解决了!

You need to create a folder within Google Drive, then add the service account email address to the list of people who can add & edit. 您需要在Google云端硬盘中创建一个文件夹,然后将服务帐户的电子邮件地址添加到可以添加和编辑的人员列表中。

Then you need to specify the folder id in your code: 然后,您需要在代码中指定文件夹ID:

$file->setParents(array("0B_xxxxxxxxxxxxxxxxxxxxxxxxx"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM