Интеграция Google Drive API с сайтом
Google Drive API позволяет загружать файлы напрямую на Drive пользователя или корпоративный диск, читать документы и таблицы, создавать папки с правами доступа. Применяется для систем документооборота, файлового хранилища, автоматической генерации отчётов.
Загрузка файлов на Drive
use Google\Client;
use Google\Service\Drive;
use Google\Service\Drive\DriveFile;
class GoogleDriveService
{
public function upload(string $localPath, string $filename, string $folderId = null): string
{
$client = $this->getClient();
$drive = new Drive($client);
$fileMetadata = new DriveFile([
'name' => $filename,
'parents' => $folderId ? [$folderId] : [],
]);
$content = file_get_contents($localPath);
$mimeType = mime_content_type($localPath);
$file = $drive->files->create($fileMetadata, [
'data' => $content,
'mimeType' => $mimeType,
'uploadType' => 'multipart',
'fields' => 'id,webViewLink,webContentLink',
]);
return $file->getId();
}
public function shareWithUser(string $fileId, string $email): void
{
$drive = new Drive($this->getClient());
$permission = new Drive\Permission([
'type' => 'user',
'role' => 'reader',
'emailAddress' => $email,
]);
$drive->permissions->create($fileId, $permission, ['sendNotificationEmail' => false]);
}
}
Resumable Upload для больших файлов
async function resumableUpload(file: File, folderId: string, accessToken: string): Promise<string> {
// Инициализация resumable session
const initResp = await fetch(
'https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable',
{
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'X-Upload-Content-Type': file.type,
'X-Upload-Content-Length': String(file.size),
},
body: JSON.stringify({ name: file.name, parents: [folderId] }),
}
);
const uploadUrl = initResp.headers.get('Location')!;
// Загрузка файла по частям
const CHUNK_SIZE = 5 * 1024 * 1024; // 5MB
let offset = 0;
while (offset < file.size) {
const chunk = file.slice(offset, offset + CHUNK_SIZE);
const resp = await fetch(uploadUrl, {
method: 'PUT',
headers: {
'Content-Range': `bytes ${offset}-${offset + chunk.size - 1}/${file.size}`,
},
body: chunk,
});
if (resp.status === 200) return (await resp.json()).id;
offset += CHUNK_SIZE;
}
throw new Error('Upload failed');
}
Автоматическое создание папок по клиенту
public function ensureClientFolder(int $clientId, string $clientName): string
{
$existing = $this->drive->files->listFiles([
'q' => "name='{$clientName}' and mimeType='application/vnd.google-apps.folder' and '{$this->rootFolderId}' in parents",
'fields' => 'files(id)',
]);
if (!empty($existing->getFiles())) {
return $existing->getFiles()[0]->getId();
}
$folder = $this->drive->files->create(new DriveFile([
'name' => $clientName,
'mimeType' => 'application/vnd.google-apps.folder',
'parents' => [$this->rootFolderId],
]), ['fields' => 'id']);
return $folder->getId();
}
Сроки
Загрузка файлов + управление папками через Service Account: 2–3 рабочих дня.







