我有一个用于使用 Google 服务帐户上传和下载文件的脚本。这看起来工作正常,但现在下载时却不行了。单击链接下载文件而不是开始下载时,会出现 Google Drive 登录页面。 老实说,我不知道对 Google Cloud 配置的 PHP 代码进行了任何更改。我检查了两者,没有发现任何变化或错误。我必须说我不是专家。
提前致谢。
我已经检查了代码和 Google 配置。我期望将文件从 php 代码上传和下载到 Google Drive。结果是上传文件很好,但是下载这些文件时会出现 Google Drive 登录窗口,而不是下载文件。
require_once 'google-api-php-client/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=googlecredentials-path-file.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(['https://www.googleapis.com/auth/drive.file']);
try {
$service = new Google_Service_Drive($client);
$google_file = new Google_Service_Drive_DriveFile();
$file_path = 'buho.jpg';
$google_file->setName($file_path);
$google_file->setParents(['Google-Drive-folder-id']);
$google_file->setDescription('File uploaded from a PHP application');
$google_file->setMimeType('image/jpeg');
$result = $service->files->create(
$google_file,
array(
'data' => file_get_contents($file_path),
'mimeType' => 'image/jpeg',
'uploadType' => 'media'
)
);
echo '<a href="https://drive.google.com/open?id=' . $result->id . '" target="_blank">' . $result->name .'</a>';
您可以生成一个链接,使用该链接时,无需登录即可访问。 注意:任何知道链接的人都可以访问
<?php
require_once "google-api-php-client/vendor/autoload.php";
putenv("GOOGLE_APPLICATION_CREDENTIALS=googlecredentials-path-file.json");
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(["https://www.googleapis.com/auth/drive.file"]);
try {
$service = new Google_Service_Drive($client);
$google_file = new Google_Service_Drive_DriveFile();
$file_path = "buho.jpg";
$google_file->setName($file_path);
$google_file->setParents(["Google-Drive-folder-id"]);
$google_file->setDescription("File uploaded from a PHP application");
$google_file->setMimeType("image/jpeg");
$result = $service->files->create($google_file, [
"data" => file_get_contents($file_path),
"mimeType" => "image/jpeg",
"uploadType" => "media",
]);
// Set permissions to create a shareable link
$permission = new Google_Service_Drive_Permission([
"type" => "anyone",
"role" => "reader",
]);
$service->permissions->create($result->id, $permission);
// Get the shareable link
$file = $service->files->get($result->id, ["fields" => "webViewLink"]);
$shareableLink = $file->webViewLink;
echo '<a href="' .
$shareableLink .
'" target="_blank">' .
$result->name .
"</a>";
} catch (Exception $e) {
// handle exception
}