2014-05-20 2 views
0

내 google 드라이브 api가 파일 업로드에 적합합니다. 그러나 나는 사용자의 드라이브의 파일 (특히 사진)을 내 웹 사이트에 어떻게 나열 할 수 있는지 혼란 스럽습니다.Google 드라이브 Api To List 사진

FYI : 다운로드 및 나열하기 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 <[email protected]> 
* 
*/ 
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

나는 문제를 해결했습니다 ... 하지만 사소한 버그로 ... 내 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++; 
     } 
    } 
?>