Google Drive Api列出照片

时间:2014-05-20 08:10:37

标签: php api google-drive-api

我的google驱动器api适用于上传文件。但我很困惑如何将用户驱动器的文件(尤其是照片)列入我的网站。

仅供参考:要下载并列出我已经复制了MediaFileUpload.php并创建了一个名为MediaFileDownload.php的新文件,然后将其所有功能从%upload%重命名为%download%。

以下是我的代码:

的index.php

    <?php
    /*
     * Copyright 2011 Google Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *     http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */

    include_once "templates/base.php";
    session_start();

    set_include_path("src/" . PATH_SEPARATOR . get_include_path());
    require_once 'Google/Client.php';
    require_once 'Google/Http/MediaFileDownload.php';
    require_once 'Google/Service/Drive.php';

    /************************************************
      ATTENTION: Fill in these values! Make sure
      the redirect URI is to this page, e.g:
      http://localhost:8080/fileupload.php
     ************************************************/
    $client_id = 'Your_Client_Id';
    $client_secret = 'Your_Client_Secret';
    $redirect_uri = 'http://localhost/MyApi/Google-Drive';

    $client = new Google_Client();
    $client->setClientId($client_id);
    $client->setClientSecret($client_secret);
    $client->setRedirectUri($redirect_uri);
    $client->addScope("https://www.googleapis.com/auth/drive");
    $service = new Google_Service_Drive($client);
    if (isset($_REQUEST['logout'])) {
      unset($_SESSION['download_token']);
    }

    if (isset($_GET['code'])) {
      $client->authenticate($_GET['code']);
      $_SESSION['download_token'] = $client->getAccessToken();
      $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
      header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
    }

    if (isset($_SESSION['download_token']) && $_SESSION['download_token']) {
      $client->setAccessToken($_SESSION['download_token']);
      if ($client->isAccessTokenExpired()) {
        unset($_SESSION['download_token']);
      }
    } else {
      $authUrl = $client->createAuthUrl();
    }

    /********************************************************
      If we're signed in then lets try to download our file.
     ********************************************************/
if ($client->getAccessToken()) {
    // This is downloading a file directly, with no metadata associated.
    echo "The code is being executed till Line No. 67.";
    /**************************************************************
    **     -----This comment is created by Ashish Shah-----     **
    ** The whole code is working if the user is not logged in.  **
    ** After user loggs in, Nothing is being displayed after    **
    ** this block.                                              **
    **************************************************************
    ** The problem is in Line No.76 to Line No.79               **
    **************************************************************/
    $file = new Google_Service_Drive_DriveFile();
    $result = $service->files->list(
        $file,
        array('downloadType' => 'media')
    );
}

    echo pageHeader("File Download - Downloading a Photo");
    if (
        $client_id == '<YOUR_CLIENT_ID>'
        || $client_secret == '<YOUR_CLIENT_SECRET>'
        || $redirect_uri == '<YOUR_REDIRECT_URI>') {
      echo missingClientSecretsWarning();
    }
    ?>
    <div class="box">
      <div class="request">
        <?php if (isset($authUrl)): ?>
          <a class='login' href='<?php echo $authUrl; ?>'>Connect Me!</a>
        <?php endif; ?>
      </div>

      <?php if (isset($result) && $result): ?>
        <div class="shortened">
          <?php var_dump($result->title); ?>
        </div>
      <?php endif ?>
    </div>
    <?php
    echo pageFooter(__FILE__);
    ?>

MediaFileDownload.php

<?php
/**
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

require_once 'Google/Client.php';
require_once 'Google/Exception.php';
require_once 'Google/Http/Request.php';
require_once 'Google/Http/REST.php';
require_once 'Google/Utils.php';

/**
 * @author Chirag Shah <chirags@google.com>
 *
 */
class Google_Http_MediaFileDownload
{
  const DOWNLOAD_MEDIA_TYPE = 'media';
  const UPLOAD_RESUMABLE_TYPE = 'resumable';

  /** @var string $mimeType */
  private $mimeType;

  /** @var string $data */
  private $data;

  /** @var bool $resumable */
  private $resumable;

  /** @var int $chunkSize */
  private $chunkSize;

  /** @var int $size */
  private $size;

  /** @var string $resumeUri */
  private $resumeUri;

  /** @var int $progress */
  private $progress;

  /** @var Google_Client */
  private $client;

  /** @var Google_Http_Request */
  private $request;

  /** @var string */
  private $boundary;

  /**
   * Result code from last HTTP call
   * @var int
   */
  private $httpResultCode;

  /**
   * @param $mimeType string
   * @param $data string The bytes you want to upload.
   * @param $resumable bool
   * @param bool $chunkSize File will be uploaded in chunks of this many bytes.
   * only used if resumable=True
   */
  public function __construct(
      Google_Client $client,
      Google_Http_Request $request,
      $mimeType,
      $data,
      $resumable = false,
      $chunkSize = false,
      $boundary = false
  ) {
    $this->client = $client;
    $this->request = $request;
    $this->mimeType = $mimeType;
    $this->data = $data;
    $this->size = strlen($this->data);
    $this->resumable = $resumable;
    if (!$chunkSize) {
      $chunkSize = 256 * 1024;
    }
    $this->chunkSize = $chunkSize;
    $this->progress = 0;
    $this->boundary = $boundary;

    // Process Media Request
    $this->process();
  }

  /**
   * Set the size of the file that is being uploaded.
   * @param $size - int file size in bytes
   */
  public function setFileSize($size)
  {
    $this->size = $size;
  }

  /**
   * Return the progress on the upload
   * @return int progress in bytes uploaded.
   */
  public function getProgress()
  {
    return $this->progress;
  }

  /**
   * Return the HTTP result code from the last call made.
   * @return int code
   */
  public function getHttpResultCode()
  {
    return $this->httpResultCode;
  }

  /**
   * Send the next part of the file to upload.
   * @param [$chunk] the next set of bytes to send. If false will used $data passed
   * at construct time.
   */
  public function nextChunk($chunk = false)
  {
    if (false == $this->resumeUri) {
      $this->resumeUri = $this->getResumeUri();
    }

    if (false == $chunk) {
      $chunk = substr($this->data, $this->progress, $this->chunkSize);
    }

    $lastBytePos = $this->progress + strlen($chunk) - 1;
    $headers = array(
      'content-range' => "bytes $this->progress-$lastBytePos/$this->size",
      'content-type' => $this->request->getRequestHeader('content-type'),
      'content-length' => $this->chunkSize,
      'expect' => '',
    );

    $httpRequest = new Google_Http_Request(
        $this->resumeUri,
        'PUT',
        $headers,
        $chunk
    );

    if ($this->client->getClassConfig("Google_Http_Request", "enable_gzip_for_downloads")) {
      $httpRequest->enableGzip();
    } else {
      $httpRequest->disableGzip();
    }

    $response = $this->client->getIo()->makeRequest($httpRequest);
    $response->setExpectedClass($this->request->getExpectedClass());
    $code = $response->getResponseHttpCode();
    $this->httpResultCode = $code;

    if (308 == $code) {
      // Track the amount downloaded.
      $range = explode('-', $response->getResponseHeader('range'));
      $this->progress = $range[1] + 1;

      // Allow for changing download URLs.
      $location = $response->getResponseHeader('location');
      if ($location) {
        $this->resumeUri = $location;
      }

      // No problems, but upload not complete.
      return false;
    } else {
      return Google_Http_REST::decodeHttpResponse($response);
    }
  }

  /**
   * @param $meta
   * @param $params
   * @return array|bool
   * @visible for testing
   */
  private function process()
  {
    $postBody = false;
    $contentType = false;

    $meta = $this->request->getPostBody();
    $meta = is_string($meta) ? json_decode($meta, true) : $meta;

    $downloadType = $this->getDownloadType($meta);
    $this->request->setQueryParam('downloadType', $downloadType);
    $this->transformToDownloadUrl();
    $mimeType = $this->mimeType ?
        $this->mimeType :
        $this->request->getRequestHeader('content-type');

    if (self::DOWNLOAD_RESUMABLE_TYPE == $downloadType) {
      $contentType = $mimeType;
      $postBody = is_string($meta) ? $meta : json_encode($meta);
    } else if (self::DOWNLOAD_MEDIA_TYPE == $downloadType) {
      $contentType = $mimeType;
      $postBody = $this->data;
    } else if (self::DOWNLOAD_MULTIPART_TYPE == $downloadType) {
      // This is a multipart/related upload.
      $boundary = $this->boundary ? $this->boundary : mt_rand();
      $boundary = str_replace('"', '', $boundary);
      $contentType = 'multipart/related; boundary=' . $boundary;
      $related = "--$boundary\r\n";
      $related .= "Content-Type: application/json; charset=UTF-8\r\n";
      $related .= "\r\n" . json_encode($meta) . "\r\n";
      $related .= "--$boundary\r\n";
      $related .= "Content-Type: $mimeType\r\n";
      $related .= "Content-Transfer-Encoding: base64\r\n";
      $related .= "\r\n" . base64_encode($this->data) . "\r\n";
      $related .= "--$boundary--";
      $postBody = $related;
    }

    $this->request->setPostBody($postBody);

    if (isset($contentType) && $contentType) {
      $contentTypeHeader['content-type'] = $contentType;
      $this->request->setRequestHeaders($contentTypeHeader);
    }
  }

  private function transformToDownloadUrl()
  {
    $base = $this->request->getBaseComponent();
    $this->request->setBaseComponent($base . '/download');
  }

  /**
   * Valid download types:
   * - resumable (DOWNLOAD_RESUMABLE_TYPE)
   * - media (DOWNLOAD_MEDIA_TYPE)
   * @param $meta
   * @return string
   * @visible for testing
   */
  public function getDownloadType($meta)
  {
    if ($this->resumable) {
      return self::DOWNLOAD_RESUMABLE_TYPE;
    }

    if (false == $meta && $this->data) {
      return self::DOWNLOAD_MEDIA_TYPE;
    }

    return self::DOWNLOAD_MULTIPART_TYPE;
  }

  private function getResumeUri()
  {
    $result = null;
    $body = $this->request->getPostBody();
    if ($body) {
      $headers = array(
        'content-type' => 'application/json; charset=UTF-8',
        'content-length' => Google_Utils::getStrLen($body),
        'x-download-content-type' => $this->mimeType,
        'x-download-content-length' => $this->size,
        'expect' => '',
      );
      $this->request->setRequestHeaders($headers);
    }

    $response = $this->client->getIo()->makeRequest($this->request);
    $location = $response->getResponseHeader('location');
    $code = $response->getResponseHttpCode();

    if (200 == $code && true == $location) {
      return $location;
    }
    throw new Google_Exception("Failed to start the resumable download");
  }
}

请尝试解决我的问题。 谢谢,

1 个答案:

答案 0 :(得分:1)

我已经解决了这个问题...... 但是有了小错误......我的api无法获取除.jpg文件之外的其他内容。它甚至无法获取.jpeg ...请解决此问题...否则一切正常... 这是新的index.php文件。

的index.php

    <?php
    /*
     * Copyright 2011 Google Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *     http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */

    include_once "templates/base.php";
    session_start();

    set_include_path("src/" . PATH_SEPARATOR . get_include_path());
    require_once 'Google/Client.php';
    require_once 'Google/Http/MediaFileDownload.php';
    require_once 'Google/Service/Drive.php';

    /************************************************
      ATTENTION: Fill in these values! Make sure
      the redirect URI is to this page, e.g:
      http://localhost:8080/fileupload.php
     ************************************************/
    $client_id = 'Your_Client_Id';
    $client_secret = 'Your_Client_Secret';
    $redirect_uri = 'http://localhost/MyApi/Google-Drive';

    $client = new Google_Client();
    $client->setClientId($client_id);
    $client->setClientSecret($client_secret);
    $client->setRedirectUri($redirect_uri);
    $client->addScope("https://www.googleapis.com/auth/drive");
    $service = new Google_Service_Drive($client);

    if (isset($_REQUEST['logout'])) {
        unset($_SESSION['download_token']);
    }

    if (isset($_GET['code'])) {
        $client->authenticate($_GET['code']);
        $_SESSION['download_token'] = $client->getAccessToken();
        $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
        header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
    }

    if (isset($_SESSION['download_token']) && $_SESSION['download_token']) {
        $client->setAccessToken($_SESSION['download_token']);
        if ($client->isAccessTokenExpired()) {
            unset($_SESSION['download_token']);
        }
    } else {
        $authUrl = $client->createAuthUrl();
    }

    /********************************************************
      If we're signed in then lets try to download our file.
     ********************************************************/
    if ($client->getAccessToken()) {
    // This is downloading a file directly, with no metadata associated.
    $file = new Google_Service_Drive_DriveFile();
    $result = $service->files->listFiles(
        $file,
        array('downloadType' => 'media')
    );
}
echo pageHeader("File Download - Downloading a Photo");
if(
        $client_id == '<YOUR_CLIENT_ID>' ||
        $client_secret == '<YOUR_CLIENT_SECRET>' ||
        $redirect_uri == '<YOUR_REDIRECT_URI>'
    ) {
    echo missingClientSecretsWarning();
}
?>
<div>
    <?php if (isset($authUrl)): ?>
    <a class='login' href='<?php echo $authUrl; ?>'>Log In To Your Google Account!</a>
    <?php endif; ?>
</div>
<br>Result:<br><pre>
<?php print_r($result)?>
</pre><br><br>
<?php
    if (isset($result)){
        $i=0;
        echo "Image Path = ".$result['modelData']['items'][$i]['thumbnailLink']."<br>";
        foreach ($result as $key => $value){
            if(strcmp($result['modelData']['items'][$i]['mimeType'],'image/')){
                echo "Entered if cond";
?>
                <div>
                    <img src="<?php echo $result['modelData']['items'][$i]['thumbnailLink'];?>">
                </div>
<?php
            }
            $i++;
        }
    }
?>