谷歌云端硬盘API - 在自己的帐户中上传文件,带有签名 - PHP



我有一个网站,用户在其中填写表单,当他们单击保存时,我将详细信息添加到数据库中并创建该数据的csv。

不想将该csv保存在我的服务器中,而是想将其保存到我自己的Google云端硬盘中。

因此,我无法向用户显示登录弹出窗口,因为我不想在他们的帐户中上传,如何在不打扰用户的情况下将该文件上传到我的帐户中(在后台(?

我在互联网上尝试了许多解决方案,例如"简单文件上传,服务帐户等"。

我认为服务帐户服务可以在这里帮助我,但没有得到任何适当的解决方案。

任何帮助将不胜感激。

请注意

,如果您使用免费的@gmail.com 帐户,则无法做到这一点。为此,您需要拥有 G Suite 帐号,因为您需要启用网域范围委派。由于您没有发布有关您尝试过的解决方案的任何代码,因此我无法确切地说出您希望如何实现这一目标;不过,下面是一个上传 CSV 文件的示例。

<?php session_start(); 
require_once "vendor/autoload.php"; //include php client library
// define service account credentials
putenv('GOOGLE_APPLICATION_CREDENTIALS=service_account_credentials.json');
//set the required scopes
$scopes = array('https://www.googleapis.com/auth/drive');
$client= new Google_Client(); // Create client object
$client->useApplicationDefaultCredentials(); // Set service account credentials
$client->addScope($scopes); //Set scopes to client object
$client->setSubject("email@domain.com"); // impersonate user
$driveService = new Google_Service_Drive($client); // define service to be rquested
//Create new drive file metadata
$fileMetadata = new Google_Service_Drive_DriveFile(
  array('name' => 'PeopleList.csv') //set file name
);
//Construct CSV data
$content = array(
  array("Name", "Age", "Gender"), // CSV Header or First row
  array("John Doe", "27", "Male"), // Row 2
  array("Alex Wright", "24", "Female"), // Row 3
  array("Elli Smith", "25", "Female") // Row 4
);
$fileName = "CSV_Test.csv"; // define temp csv file name
$csvFile = fopen($fileName, 'w'); // open file to write on it
//save content to csv file
foreach ($content as $row) {
  fputcsv($csvFile, $row);
}
fclose($csvFile); // close csv file
$csvData = file_get_contents($fileName); //extract csv file data
//upload csv to drive
$file = $driveService->files->create($fileMetadata, array(
  'data' => $csvData,
  'mimeType' => 'text/csv',
  'uploadType' => 'multipart'
  )
);
//delete temp csv file
unlink($fileName);
print_r($file);
?>

最新更新