【问题标题】:Google Drive PHP API Download fileGoogle Drive PHP API 下载文件
【发布时间】:2015-03-03 00:25:10
【问题描述】:

我在使用 php api 从谷歌驱动器下载文件时遇到问题。我设法将文件上传到文件夹中的谷歌驱动器,并且 $service->files->insert 返回给我具有属性 downloadUrl 的文件资源,但是当我重定向到该 url 时,它不起作用。我收到 401 错误。为什么会这样?我需要做什么才能完成这项工作?

代码如下:

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

$client_id = 'xxx';
$client_secret = 'yyy';
$redirect_uri = 'http://localhost/GoogleDrive/code.php';

$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);

$authUrl = $client->createAuthUrl();
header("Location: $authUrl");

和code.php

require_once 'vendor/autoload.php';
session_start();

$client_id = 'xxx';
$client_secret = 'yyy';
$redirect_uri = 'http://localhost/GoogleDrivePayload/code.php';

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

$service = new Google_Service_Drive($client);


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

if (isset($_SESSION['upload_token']) && $_SESSION['upload_token']) {
    $client->setAccessToken($_SESSION['upload_token']);
    if ($client->isAccessTokenExpired()) {
        unset($_SESSION['upload_token']);
    }
}

if ($client->getAccessToken()) {
    $file = new Google_Service_Drive_DriveFile();
    $file->setTitle("hello.exe");
    $file->setDescription("LALALALALAL");
    $file->setMimeType('application/x-msdos-program');

    $parent = new Google_Service_Drive_ParentReference();
    $parent->setId("zzz");
    $file->setParents(array($parent));

    $data = file_get_contents('hello.exe');
    $createdFile = $service->files->insert($file, array(
            'data' => $data,
            'mimeType' => 'application/x-msdos-program',
            'uploadType' => 'multipart',
            "visibility" => "DEFAULT"
    ));

    header("Location: " . $createdFile->downloadUrl);
}

【问题讨论】:

    标签: php google-drive-api


    【解决方案1】:

    downloadUrl 正是它所说的,即。您的 PHP 应用程序可用于获取文件的 URL。您几乎永远不会将浏览器重定向到该 URL,如果您这样做了(您可能真的不想这样做),您需要将有效的访问令牌附加到该 URL 以修复 401。

    【讨论】:

    • 我已经尝试使用 file_get_contents($createdFile->downloadUrl),但仍然出现 401 错误。
    • 401 仅表示您的访问令牌不正确。您需要查看您是如何管理您的代币的。尝试记录底层 http 以查看发生了什么。
    • 能否请您分享您用于从谷歌驱动器下载文件的包
    猜你喜欢
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 2015-02-06
    • 2022-01-03
    • 2018-10-26
    相关资源
    最近更新 更多