0
我上傳文件使用API可讓Google直接驅動文件,以谷歌驅動器,但實際上我有後續的方法:發送使用API和輸入文件
- 使用文件輸入 將文件發送到服務器
- 使用API將文件從服務器發送到谷歌驅動器
我有這個編碼工作爲我上面提到的。 (代碼是內部的一個框架)
public function actionCallgdrive() {
$client = new Google_Client();
$client->setApplicationName("Google Drive");
$client->setAuthConfig((dirname(__FILE__)) . '/client_secret.json');
$client->setRedirectUri('http://' . $_SERVER['SERVER_NAME'] . Url::to(['content/callgdrive']));
$client->addScope(Google_Service_Drive::DRIVE);
$client->setAccessType('offline');
if (!isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
$this->redirect($auth_url);
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$this->redirect(['content/google-drive']);
}
}
public function actionGoogleDrive($filename) {
$client = new Google_Client();
$client->setApplicationName("Google Drive");
$client->setAuthConfig((dirname(__FILE__)) . '/client_secret.json');
$client->addScope(Google_Service_Drive::DRIVE);
$client->setAccessType('offline');
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
if ($client->isAccessTokenExpired()) {
$refreshToken = $this->getRefreshTokenFromDatabase();
$client->refreshToken($refreshToken);
$newAccessToken = $client->getAccessToken();
$newAccessToken['refresh_token'] = $refreshToken;
$this->setRefreshTokenIntoDatabase($newAccessToken);
$_SESSION['access_token'] = $newAccessToken;
}
set_time_limit(0);
$gdrive_service = new Google_Service_Drive($client);
$file = new Google_Service_Drive_DriveFile();
$folderId = 'dfghjtyguygyuuuuuuuuuuu';
$file->setName($filename);
$file->setParents([$folderId]);
$chunkSizeBytes = 1 * 1024 * 1024;
$client->setDefer(true);
$request = $gdrive_service->files->create($file);
$media = new Google_Http_MediaFileUpload(
$client, $request, 'application/zip', null, true, $chunkSizeBytes
);
$media->setFileSize(filesize(Yii::getAlias('@webroot').'/content/' . $filename));
$status = false;
$handle = fopen(Yii::getAlias('@webroot').'/content/' . $filename, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
$result = false;
if ($status != false) {
$result = $status;
$fileId = $result->getId();
}
fclose($handle);
$client->setDefer(false);
} else {
$this->actionCallgdrive();
}
}
public function actionUpload()
{
$model = new UploadForm();
if (Yii::$app->request->post()) {
$model->file = UploadedFile::getInstance($model, 'file');
if ($model->validate()) {
$model->file->saveAs(Yii::getAlias('@webroot').'/content/' . $model->file->baseName . '.' . $model->file->extension);
$filename = $model->file->baseName . '.' . $model->file->extension;
$this->actionGoogleDrive($filename);
}
}
return $this->render('upload', ['model' => $model]);
}
所以,我的問題是:我可以用文件輸入直接發送文件,谷歌驅動器?如果是的話,我該怎麼做?
感謝您的獨特答覆。 我曾嘗試過這種方法,我得到這個錯誤:「調用未定義的方法Google_Service_Drive_Resource_Files :: insert()」我認爲這種方法是從舊的api版本。 –