【问题标题】:File download from Google API v3 in PHP在 PHP 中从 Google API v3 下载文件
【发布时间】:2016-08-23 13:31:15
【问题描述】:

一直在寻找使用here 提到的 API 从谷歌驱动器下载文件。在流程中,能够通过用户的身份验证,并且能够使用以下代码列出文件。

 echo "<br>" . count($results->getFiles()). " File(s) found" ; 
        echo "<hr>";
        foreach ($results->getFiles() as $file) {
            echo "File Name is " . $file->getName() . " And file ID is ". $file->getId() . " Type is ".$file->getMimeType() ."<br><pre>";
            print_r($file);
            echo "</pre><hr>";
        }

输出类似于

100 File(s) found
File Name is invoice receipt.pdf And file ID is 0B5CWXJTNwALMOEJkdzFvMVVsVFE Type is application/pdf
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] => 0B5CWXJTNwALMOEJkdzFvMVVsVFE
    [imageMediaMetadataType:protected] => Google_Service_Drive_DriveFileImageMediaMetadata
    [imageMediaMetadataDataType:protected] => 
    [isAppAuthorized] => 
    [kind] => drive#file
    [lastModifyingUserType:protected] => Google_Service_Drive_User
    [lastModifyingUserDataType:protected] => 
    [md5Checksum] => 
    [mimeType] => application/pdf
    [modifiedByMeTime] => 
    [modifiedTime] => 
    [name] => invoice receipt.pdf
    [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
        (
        )

)

现在,尝试应用如下下载代码

$fileId = '0B5CWXJTNwALMOEJkdzFvMVVsVFE';
        $content = $drive_service->files->get($fileId,  array(
            'alt' => 'media' ));
        echo "<pre>";
        print_r($content->getHeaders());
        foreach ($content->getHeaders() as $name => $values) {

        header($name . ': ' . implode(', ', $values[0]));
        }

文件未下载,但可以看到如下输出

Array
(
    [X-GUploader-UploadID] => Array
        (
            [0] => AEnB2UrDOQ-mYxNd5tE5ctVr01jVTnh3ZykKviCBnEOjDRGtT_EIT2nbHLEM_f-2pZ22anDJpqMzbISzhcTTZY3PgsDj69PE-w
        )

    [Content-Type] => Array
        (
            [0] => application/pdf
        )

    [Content-Disposition] => Array
        (
            [0] => attachment
        )

    [Vary] => Array
        (
            [0] => Origin
            [1] => X-Origin
        )

    [Expires] => Array
        (
            [0] => Tue, 23 Aug 2016 13:20:18 GMT
        )

    [Date] => Array
        (
            [0] => Tue, 23 Aug 2016 13:20:18 GMT
        )

    [Cache-Control] => Array
        (
            [0] => private, max-age=0, must-revalidate
        )

    [Content-Length] => Array
        (
            [0] => 80277
        )

    [X-Goog-Hash] => Array
        (
            [0] => crc32c=5yKN2g==
        )

    [Server] => Array
        (
            [0] => UploadServer
        )

    [Alternate-Protocol] => Array
        (
            [0] => 443:quic
        )

    [Alt-Svc] => Array
        (
            [0] => quic=":443"; ma=2592000; v="35,34,33,32,31,30"
        )

)

问题:如何下载文件?

编辑

根据保罗的回答,创建了如下两个文件。这适用于 image/png、application/octet-stream、application/pdf 类型,但是 zip/rar 文件存在问题(错误:此站点无法联系到

test.php

<?php
require_once __DIR__ . '/vendor/autoload.php';
session_start();

$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->addScope(Google_Service_Drive::DRIVE);

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) 
{
    $client->setAccessToken($_SESSION['access_token']);
    $drive_service = new Google_Service_Drive($client);
    $results = $drive_service->files->listFiles();
    if (count($results->getFiles()) == 0) 
    {
        echo "No files found";
    } 
    else 
    {
        echo "<br>" . count($results->getFiles()). " File(s) found" ; 
        echo "<br><table><thead><th>File Name</th><th>File Type</th><th>Download Link</th></thead><tbody>";
        foreach ($results->getFiles() as $file) {
            echo "<tr><td>" . $file->getName() . "</td><td>" . $file->getMimeType() ."</td><td><a href='gdrivedownlaod.php?fileid=". $file->getId() . "&type=" . $file->getMimeType() . "&name=" . $file->getName() . "' target='blank'>Download</a></td></tr>";// ."<br><pre>";
            }
            echo "</tbody></table>";
    }

} 
else 
{
    $redirect_uri = 'https://abcd.co/oauth2callback';
    echo "Hello, <a href='" . $redirect_uri . "'>Log in with Drive</a>";
}

和 gdrivedownlaod.php 作为

<?php
require_once __DIR__ . '/vendor/autoload.php';
session_start();

$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->addScope(Google_Service_Drive::DRIVE);

if (isset($_GET['name']) && isset($_GET['type'])) {
//echo "We will download " . $_GET['name'] . " type " . $_GET['type'] . " with file id " . $_GET['fileid'];
    $fileId=$_GET['fileid'];
    if (isset($_SESSION['access_token']) && $_SESSION['access_token']) 
    {
        $client->setAccessToken($_SESSION['access_token']);
        $drive_service = new Google_Service_Drive($client);
        $content = $drive_service->files->get($fileId,  array(
            'alt' => 'media' ));
                $fileName = $_GET['name'];
        $headers = $content->getHeaders();

        foreach ($headers as $name => $values) {
            header($name . ': ' . implode(', ', $values));
        }
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        echo $content->getBody();
        //echo "<script>window.close();</script>";
        exit;
    }
    else
    {
        session_destroy();
        session_unset();
        header('Location: test.php'); 
    }

}
else
echo "incorrect files ";

【问题讨论】:

  • 感谢保罗,已更改。对解决方案有任何想法吗?
  • 首先尝试docs 中的建议,即下载文件向文件的资源 URL 发出授权的 HTTP GET 请求并包含查询参数 alt=media。如果此方法对您有效,请尝试仔细检查您使用的代码。请注意,下载文件需要用户至少具有读取权限。您的应用程序必须获得允许读取文件内容的范围的授权。例如,使用 drive.readonly.metadata 范围的应用将无权下载文件内容
  • 感谢@KENdi。我拥有完整的驱动器访问权限,因为我也能够获取元数据。问题是如何使用 guzzle 响应在浏览器中调度文件。

标签: php google-drive-api


【解决方案1】:
$fileName = 'xpto.pdf';
$driveService = new Google_Service_Drive($client);
$content = $driveService->files->get($fileId, array(
    'alt' => 'media'));

$headers = $content->getHeaders();
foreach ($headers as $name => $values) {
    header($name . ': ' . implode(', ', $values));
}
header('Content-Disposition: attachment; filename="' . $fileName . '"');
echo $content->getBody();
exit;

【讨论】:

  • 感谢@paulo-pinto,但它只是打印原始内容而不是导出文件
  • @Rajesh header('Content-Disposition: attachment; filename="' . $fileName . '"');用于下载和 header('Content-Disposition: inline; filename="' . $fileName . '"');在浏览器中查看。您是在新标签页中打开链接吗?
  • 已编辑问题,请检查 gdrivedownlaod.php 并提出更改建议
  • @Rajesh 我测试了您的解决方案,并且适用于 zip/tar 档案,我可以毫无问题地下载。抱歉,我帮不上忙……:(
【解决方案2】:

如上所示,$content-&gt;getHeaders() 提供了您的 HTTP 请求的相应标头信息的预期输出。

要检索文件内容,您需要$content-&gt;getResponseBody(),然后调用file_put_contents 以将数据保存到本地文件中。

【讨论】:

  • 请您帮忙完成它的完整脚本部分。我试过 print_r($content-&gt;getResponseBody()); 没有打印出来。
  • 我不擅长 PHP,无论如何你应该能够通过检查文档来弄清楚这一点(不要偷懒。如果你在尝试之后遇到特定错误,请在此处发布详细信息,我相信你会得到一些帮助)。顺便说一句,你的文件是 PDF,文件内容通常是二进制数据,我认为你不能在上面做 print_r。祝你好运。
  • 在这里提问之前我已经尝试了足够多。也尝试过图像类型,结果是一样的。即使对于 pdf,如果不打印,也期望它下载没有发生的文件。这里的问题是 SDK 仍处于测试阶段,他们的 V2 api 已经过时了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-06
相关资源
最近更新 更多