2016-04-13 83 views
2

私は、Googleドライブの写真でいっぱいのフォルダにサーバーを同期させる(一方向)システムを作りたいと思っています。PHPでGoogleドライブAPIを使用してファイルをダウンロードする

これまで私はgithub(私は作曲家を使用していません)からPHPクライアントライブラリをダウンロードし、いくつかのファイルを一覧表示しています。私は手動でこれを使用した写真の一つのIDを取得するために管理:

私はここに私が試したものだが、私は
Fatal error: Call to undefined method Google_Service_Drive_DriveFile::getDownloadUrl()を言ってエラーを取得し、IDからファイルをダウンロードすることができませんよしかし
// Print the names and IDs for up to 10 files. 
$optParams = array(
    'pageSize' => 10, 
    'fields' => "nextPageToken, files(id, name)" 
); 
$results = $service->files->listFiles($optParams); 

if (count($results->getFiles()) == 0) { 
    print "No files found.\n"; 
} else { 
    print "Files:\n"; 

    echo "<pre>"; 
    print_r($results); 
    echo "</pre>"; 
} 

ここで

<?php 
require $_SERVER['DOCUMENT_ROOT'] . '/includes/googleAPI/vendor/autoload.php'; 

define('APPLICATION_NAME', 'Drive API PHP Quickstart'); 
define('CREDENTIALS_PATH', $_SERVER['DOCUMENT_ROOT'] . '/includes/googleAPI/drive-php-quickstart.json'); 
define('CLIENT_SECRET_PATH', $_SERVER['DOCUMENT_ROOT'] . '/includes/googleAPI/client_secret.json'); 
// If modifying these scopes, delete your previously saved credentials 
// at ~/.credentials/drive-php-quickstart.json 
define('SCOPES', implode(' ', array(
     "https://www.googleapis.com/auth/drive.readonly") 
)); 

/*if (php_sapi_name() != 'cli') { 
    throw new Exception('This application must be run on the command line.'); 
}*/ 

/** 
* Returns an authorized API client. 
* @return Google_Client the authorized client object 
*/ 
function getClient() 
{ 
    $client = new Google_Client(); 
    $client->setApplicationName(APPLICATION_NAME); 
    $client->setScopes(SCOPES); 
    $client->setAuthConfigFile(CLIENT_SECRET_PATH); 
    $client->setAccessType('offline'); 

    // Load previously authorized credentials from a file. 
    $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH); 
    if (file_exists($credentialsPath)) { 
     $accessToken = file_get_contents($credentialsPath); 
    } else { 
     // Request authorization from the user. 
     $authUrl = $client->createAuthUrl(); 
     printf("Open the following link in your browser:\n%s\n", $authUrl); 
     print 'Enter verification code: '; 
     $authCode = trim(fgets(STDIN)); 

     // Exchange authorization code for an access token. 
     $accessToken = $client->authenticate($authCode); 

     // Store the credentials to disk. 
     if (!file_exists(dirname($credentialsPath))) { 
      mkdir(dirname($credentialsPath), 0700, true); 
     } 
     file_put_contents($credentialsPath, json_encode($accessToken)); 
     printf("Credentials saved to %s\n", $credentialsPath); 
    } 
    $client->setAccessToken($accessToken); 

    // Refresh the token if it's expired. 
    if ($client->isAccessTokenExpired()) { 
     $refreshToken = $client->getRefreshToken(); 
     $client->refreshToken($refreshToken); 
     $newAccessToken = $client->getAccessToken(); 
     $newAccessToken['refresh_token'] = $refreshToken; 
     file_put_contents($credentialsPath, json_encode($newAccessToken)); 
    } 
    return $client; 
} 

/** 
* Expands the home directory alias '~' to the full path. 
* @param string $path the path to expand. 
* @return string the expanded path. 
*/ 
function expandHomeDirectory($path) 
{ 
    $homeDirectory = getenv('HOME'); 
    if (empty($homeDirectory)) { 
     $homeDirectory = getenv("HOMEDRIVE") . getenv("HOMEPATH"); 
    } 
    return str_replace('~', realpath($homeDirectory), $path); 
} 

/** 
* 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->getName(); 
     print "Description: " . $file->getDescription(); 
     print "MIME type: " . $file->getMimeType(); 
     print "Download URL: : " . $file->getDownloadUrl(); 

     return $file; 
    } catch (Exception $e) { 
     print "An error occurred: " . $e->getMessage(); 
    } 
} 

/** 
* Download a file's content. 
* 
* @param Google_Service_Drive $service Drive API service instance. 
* @param Google_Service_Drive_DriveFile $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; 
    } 
} 

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


$fileId = $_GET['id']; 
$file = printFile($service, $fileId); 
echo "<br/><pre>"; 
print_r($file); 
echo "</pre><hr/>"; 
print_r(downloadFile($service, $file)); 

は、あなたが見ることができるように、リンクが含まれている必要がありますフィールドが空白のように見える、printFile()の応答です。私はv2およびAPIのv3およびとの差にとしても不明確だ

[0] => Google_Service_Drive_DriveFile Object 
         (
          [collection_key:protected] => spaces 
          [appProperties] => 
          [capabilitiesType:protected] => Google_Service_Drive_DriveFileCapabilities 
          [capabilitiesDataType:protected] => 
          [contentHintsType:protected] => Google_Service_Drive_DriveFileContentHints 
          [contentHintsDataType:protected] => 
          [createdTime] => 
          [description] => 
          [explicitlyTrashed] => 
          [fileExtension] => 
          [folderColorRgb] => 
          [fullFileExtension] => 
          [headRevisionId] => 
          [iconLink] => 
          [id] => XXXXXXX //I've removed this, but it is a valid id, I've checked. 
          [imageMediaMetadataType:protected] => Google_Service_Drive_DriveFileImageMediaMetadata 
          [imageMediaMetadataDataType:protected] => 
          [kind] => 
          [lastModifyingUserType:protected] => Google_Service_Drive_User 
          [lastModifyingUserDataType:protected] => 
          [md5Checksum] => 
          [mimeType] => 
          [modifiedByMeTime] => 
          [modifiedTime] => 
          [name] => blue_and_white_diagonal_stripes_background_seamless.gif 
          [originalFilename] => 
          [ownedByMe] => 
          [ownersType:protected] => Google_Service_Drive_User 
          [ownersDataType:protected] => array 
          [parents] => 
          [permissionsType:protected] => Google_Service_Drive_Permission 
          [permissionsDataType:protected] => array 
          [properties] => 
          [quotaBytesUsed] => 
          [shared] => 
          [sharedWithMeTime] => 
          [sharingUserType:protected] => Google_Service_Drive_User 
          [sharingUserDataType:protected] => 
          [size] => 
          [spaces] => 
          [starred] => 
          [thumbnailLink] => 
          [trashed] => 
          [version] => 
          [videoMediaMetadataType:protected] => Google_Service_Drive_DriveFileVideoMediaMetadata 
          [videoMediaMetadataDataType:protected] => 
          [viewedByMe] => 
          [viewedByMeTime] => 
          [viewersCanCopyContent] => 
          [webContentLink] => 
          [webViewLink] => 
          [writersCanShare] => 
          [internal_gapi_mappings:protected] => Array 
           (
           ) 

          [modelData:protected] => Array 
           (
           ) 

          [processed:protected] => Array 
           (
           ) 

         ) 

それらを混乱しているかも?どちらも同じquickstart.phpコードを使用しているようです。

ありがとうございました!

答えて

0

ご不明な点は、ドライブv2とv3の違いは何ですか。ここ

変更の一部である:V3とgetTitle()に)V2でgetItems()方法はgetFiles(なろう

  • getName()となるであろう。

  • デフォルトでは、フルリソースは返されなくなりました。 fieldsクエリパラメータを使用して、返される特定のフィールドを要求します。指定されていない場合、一般的に使用されるフィールドのサブセットのみが返されます。

  • すべての更新操作が今の代わりにPUT

  • のPATCHを使用exportLinksフィールドがファイルから削除されました。 Googleドキュメントをエクスポートするには、代わりにfiles.exportメソッドを使用してください。

詳しくは、documentationを参照してください。

ファイルのダウンロードで問題が発生しました。これをチェックしてみてくださいSO question

これによれば、downloadUrlsを取得するには、ファイルのメタデータを取得する必要があります。これは、GETメソッドを使用して行うことができます。このメソッドはFile Resourceの表現を返します。このリソースにはdownloadUrlというプロパティがあります。ファイルにアクセスしてURLを取得できる場合は、認証設定に問題はありません。特定のドライブファイルにアクセスできないアクセス権の問題がある可能性があります。

詳細はSO questionをご確認ください

関連する問題