Uploads a file to the Gemini File API, making it available for use in generation requests with large files, videos, or audio.
Method Signature
client.files.upload(
file: Union[str, os.PathLike[str], io.IOBase],
config: Optional[UploadFileConfigOrDict] = None
) -> File
Parameters
file
string | PathLike | IOBase
required
The file to upload.Can be:
- A file path as a string:
"/path/to/file.pdf"
- A PathLike object:
Path("document.pdf")
- An IOBase object (file handle): Must be opened in binary mode (
'rb') and be seekable
When using an IOBase object (file handle), ensure:
- The file is opened in binary mode (not text mode)
- The file is opened in blocking mode (the default)
- The stream is seekable (supports
seek() operations)
Optional configuration for the upload.Available options:
display_name: Human-readable name for the file
mime_type: MIME type (auto-detected if not provided)
name: Custom resource name
http_options: Custom HTTP request options
Returns
A File object containing:
name: The resource name (e.g., "files/abc123")
uri: The URI to reference in API calls
display_name: Human-readable name
mime_type: The file’s MIME type
size_bytes: File size in bytes
create_time: When the file was uploaded
update_time: Last update time
expiration_time: When the file will be deleted
state: Upload state (PROCESSING, ACTIVE, or FAILED)
Examples
Upload PDF Document
from google import genai
client = genai.Client(api_key='your-api-key')
# Upload file
file = client.files.upload(file='research_paper.pdf')
print(f"Uploaded file: {file.name}")
print(f"URI: {file.uri}")
print(f"Size: {file.size_bytes} bytes")
Upload with Display Name
# Upload with custom display name
file = client.files.upload(
file='document.pdf',
config={'display_name': 'Q4 Financial Report'}
)
print(f"File: {file.display_name}")
print(f"MIME type: {file.mime_type}")
Upload Video File
# Upload video
video_file = client.files.upload(
file='presentation.mp4',
config={'display_name': 'Product Demo Video'}
)
print(f"Video uploaded: {video_file.name}")
print(f"State: {video_file.state}")
Upload from File Handle
# Upload using file handle
with open('data.json', 'rb') as f:
file = client.files.upload(
file=f,
config={
'display_name': 'User Data',
'mime_type': 'application/json'
}
)
print(f"Uploaded: {file.name}")
Upload and Use in Prompt
from google.genai import types
# Upload file
file = client.files.upload(file='annual_report.pdf')
# Wait for processing if needed
import time
while file.state == 'PROCESSING':
time.sleep(1)
file = client.files.get(name=file.name)
# Use in generation
response = client.models.generate_content(
model='gemini-2.0-flash',
contents=[
types.Part(file_data=types.FileData(file_uri=file.uri)),
'Summarize the key points from this report'
]
)
print(response.text)
Upload Multiple Files
# Upload multiple documents
file_paths = ['doc1.pdf', 'doc2.pdf', 'doc3.pdf']
files = []
for path in file_paths:
file = client.files.upload(file=path)
files.append(file)
print(f"Uploaded: {file.display_name or file.name}")
# Use all files in one prompt
parts = [
types.Part(file_data=types.FileData(file_uri=f.uri))
for f in files
]
parts.append('Compare and contrast these documents')
response = client.models.generate_content(
model='gemini-2.0-flash',
contents=parts
)
print(response.text)
Async Upload
import asyncio
from google import genai
client = genai.Client(api_key='your-api-key')
async def upload_example():
# Upload file asynchronously
file = await client.aio.files.upload(file='document.pdf')
print(f"Uploaded: {file.name}")
return file
asyncio.run(upload_example())
Upload with Custom MIME Type
# Explicitly set MIME type
file = client.files.upload(
file='data.custom',
config={'mime_type': 'application/octet-stream'}
)
Upload Audio File
# Upload audio for transcription or analysis
audio = client.files.upload(
file='podcast.mp3',
config={'display_name': 'Podcast Episode 1'}
)
# Use in prompt
response = client.models.generate_content(
model='gemini-2.0-flash',
contents=[
types.Part(file_data=types.FileData(file_uri=audio.uri)),
'Transcribe this audio and provide a summary'
]
)
print(response.text)
File Lifecycle
Uploaded files are automatically deleted after 48 hours. Plan your workflows accordingly or re-upload files as needed.
Error Handling
try:
file = client.files.upload(file='document.pdf')
print(f"Success: {file.name}")
except FileNotFoundError:
print("File not found")
except Exception as e:
print(f"Upload failed: {e}")
API Availability
This method is only available in the Gemini API (not Vertex AI).For Vertex AI, you should:
- Store files in Google Cloud Storage (GCS)
- Use
files.register_files() to register GCS URIs
- Or use direct GCS URIs in prompts