通过API保存Google云端硬盘中的图片

时间:2016-12-10 17:11:44

标签: php google-drive-api

我已关注this tutorial,一切正常,我可以看到名称和ID的列表。

当我尝试在我的服务器上保存此图像时,保存的文件为空。我从命令行运行这个脚本。

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);

// Print the names and IDs for up to 10 files.
$optParams = array(
  'pageSize' => 1,
  'fields' => 'nextPageToken, files(id, name)'
);
$results = $service->files->listFiles($optParams);

if (count($results->getFiles()) == 0) {
  print "No files found.\n";
} else {
  print "Files:\n";
  foreach ($results->getFiles() as $file) {
    printf("%s (%s)\n", $file->getName(), $file->getId());

  $fileIdr = $file->getId();
  }
 // $content = $service->files->export($fileIdr, 'image/jpeg', array('alt' => 'media' ));
  $content = $service->files->get($fileIdr, array('alt' => 'media' ));

    var_dump($content);

  $zdjecie = '/home/bachus03/domains/bachus03.vot.pl/public_html/fb/public/test.jpg';
  file_put_contents($zdjecie, $content);

1 个答案:

答案 0 :(得分:0)

要获取文件内容,请使用带有getDownloadUrl()函数的Google示例。 Source here

   
/*
*  
* Print a file's metadata.
* 
* @param Google_Service_Drive $service Drive API service instance.  
* @param string $fileId ID of the file to print metadata for.  
*/ 
function printFile($service, $fileId) {   
  try {
    $file = $service->files->get($fileId);

    print "Title: " . $file->getTitle();
    print "Description: " . $file->getDescription();
    print "MIME type: " . $file->getMimeType();   } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();   
  }
}

/*
*  
* Download a file's content.  
*  
* @param Google_Service_Drive $service Drive API service instance.  
* @param File $file Drive File instance.  
* @return String The file's content if successful, null otherwise.  
*/ 
function downloadFile($service, $file) {   
  $downloadUrl = $file->getDownloadUrl();   
  if ($downloadUrl) {
    $request = new Google_Http_Request($downloadUrl, 'GET', null, null);
    $httpRequest = $service->getClient()->getAuth()->authenticatedRequest($request);
    if ($httpRequest->getResponseHttpCode() == 200) {
      return $httpRequest->getResponseBody();
    } else {
      // An error occurred.
      return null;
    }   
  } else {
    // The file doesn't have any content stored on Drive.
    return null;
  }
}

编辑:查看文件资源参考:https://developers.google.com/drive/v3/reference/files#resource 您可以使用webContentLink属性来获取我认为的内容。

相关问题