Skip to content

Instantly share code, notes, and snippets.

@michabbb
Created October 22, 2024 17:13
Show Gist options
  • Save michabbb/3e170577c9ef2cf54c0336c394735bf8 to your computer and use it in GitHub Desktop.
Save michabbb/3e170577c9ef2cf54c0336c394735bf8 to your computer and use it in GitHub Desktop.
Upload Files to the Gemini API
<?php
namespace App\Services\google;
use Exception;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
class Gemini
{
private string $baseUrl = 'https://generativelanguage.googleapis.com/upload/v1beta/files';
private string $apiKey;
public function __construct(string $apiKey)
{
$this->apiKey = $apiKey;
}
/**
* @throws ConnectionException
* @throws Exception
*/
public function uploadFile(string $filePath, string $displayName): array
{
$fileSize = filesize($filePath);
$mimeType = mime_content_type($filePath);
// Initial resumable request
$response = Http::withHeaders([
'X-Goog-Upload-Protocol' => 'resumable',
'X-Goog-Upload-Command' => 'start',
'X-Goog-Upload-Header-Content-Length' => $fileSize,
'X-Goog-Upload-Header-Content-Type' => $mimeType,
'Content-Type' => 'application/json',
])->post($this->baseUrl . '?key=' . $this->apiKey, [
'file' => ['display_name' => $displayName]
]);
$uploadUrl = $response->header('X-Goog-Upload-URL');
if (!$uploadUrl) {
throw new \RuntimeException('Failed to get upload URL');
}
// Upload the actual bytes
$fileContent = file_get_contents($filePath);
$uploadResponse = Http::withHeaders([
'Content-Length' => $fileSize,
'X-Goog-Upload-Offset' => 0,
'X-Goog-Upload-Command' => 'upload, finalize',
])->withBody($fileContent, $mimeType)
->post($uploadUrl);
return $uploadResponse->json();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment