簡體   English   中英

Google Drive Api列出照片

[英]Google Drive Api To List Photos

我的Google Drive 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");
  }
}

請嘗試解決我的問題。 謝謝,

我已經解決了問題...但是有一個小錯誤...我的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++;
        }
    }
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM