Integrating Google Drive API with Website
Google Drive API allows uploading files directly to a user's Drive or corporate storage, reading documents and spreadsheets, and creating folders with access controls. Used for document management systems, file storage, and automated report generation.
Uploading Files to 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 for Large Files
async function resumableUpload(file: File, folderId: string, accessToken: string): Promise<string> {
// Initialize 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')!;
// Upload file in chunks
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');
}
Automatic Folder Creation per Client
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();
}
Timeline
File uploads + folder management via Service Account: 2–3 business days.







