在单个请求中下载文件内容和元数据

在单个请求中下载文件内容和元数据

本文介绍了带有PHP客户端2.0的Google Drive API V3-在单个请求中下载文件内容和元数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用带有Drive API V3的PHP客户端v2.0从Google Drive下载文件.

I am trying to download files from Google Drive using PHP client v2.0 with Drive API V3.

是否可以在单个HTTP请求中检索文件的正文和元数据?

Is it possible to retrieve file's body and metadata in a single HTTP request?

'alt = media'提供给->文件-> get()会返回 GuzzleHttp \ Psr7 \ Response 可以运行-> getBody()-> __ toString().

Supplying 'alt=media' to ->files->get() returns GuzzleHttp\Psr7\Response upon which I can run ->getBody()->__toString().

如果我不提供'alt = media',则返回的 Google_Service_Drive_DriveFile 具有所有元数据,但没有正文.

If I do not provide 'alt=media', then Google_Service_Drive_DriveFile is returned that has all the metadata, but does not have body.

问题.

是否可以在同一请求中同时获取元数据和正文?

Is it possible to get both metadata and body in the same request?

推荐答案

尝试如下操作:

<?php

///首先查看: https://developers.google.com/api-client-library/php/auth/web-app

require_once __DIR__ . '/vendor/autoload.php';

//更改为您的时区date_default_timezone_set('太平洋/奥克兰');

//change to your timezone date_default_timezone_set('Pacific/Auckland');

$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setIncludeGrantedScopes(true);

//将范围更改为所需的范围

//change scopes to the ones you need

$client->addScope(Google_Service_Drive::DRIVE_FILE, Google_Service_Drive::DRIVE_APPDATA, Google_Service_Drive::DRIVE, Google_Service_Drive::DRIVE_METADATA);
$accessToken = json_decode(file_get_contents('credentials.json'), true);
$client->setAccessToken($accessToken);

///刷新令牌(如果令牌已过期).Google会在一个小时后将其过期

//Refresh the token if it's expired. Google expires it after an hour so necessary

if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents('credentials.json', json_encode($client->getAccessToken()));
}

$service = new Google_Service_Drive($client);
$results = $service->files->listFiles($optParams);
$fileId = 'yourfileid;
$file = $service->files->get($fileId, array('alt' => 'media'));
file_put_contents("hello.pdf",$file->getBody());
?>

这篇关于带有PHP客户端2.0的Google Drive API V3-在单个请求中下载文件内容和元数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 19:18