dtot74529 2017-10-17 03:43
浏览 48

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

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).

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:

{
 "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. My aim is to create a function for uploading files stored on my server, so I don't require an oAuth consent screen.

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>");
  • 写回答

1条回答 默认 最新

  • dongtan6543 2017-10-17 15:57
    关注

    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.

    Then you need to specify the folder id in your code:

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

报告相同问题?