繁体   English   中英

Google Drive PHP API下载文件

[英]Google Drive PHP API Download file

我在使用php API从Google驱动器下载文件时遇到问题。 我设法将文件上传到文件夹中的Google驱动器,并且$ 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);
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM