我正在尝试使用 php 将 google drive jpg 下载到服务器,以便将其保存为可用的 jpg,例如手动下载时。
我可以从 filemeta 获取 getWebContentLink 并保存扩展名为 .jpg 的“a”文件:
$filemeta = $this->service->files->get($id,[
"fields"=>"*"
]);
$filename = public_path().'/test.jpg';
$url=$filemeta->getWebContentLink();
file_put_contents($filename, fopen($url, 'r'));
然而,这不是真正的 jpg,确实无法使用<img src="/test.jpg" />元素显示。
设置:
public function __construct() {
$this->getClient();
$this->service= new Google_Service_Drive($this->client);
}
/**
* @return Google_Client
* @throws \Google_Exception
*/
protected function getClient() {
$client = new Google_Client();
$client->setApplicationName('Google Drive API PHP Quickstart');
//20200521$client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->setScopes(Google_Service_Drive::DRIVE_READONLY);
// https://www.googleapis.com/auth/drive.readonly
$client->setAuthConfig(base_path().'/apicredentials/google/credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = base_path().'/apicredentials/google/token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
}
}
}
叮当猫咪