0
# File Management
1
2
The Files module provides file upload and management capabilities for use in generation requests (Gemini API only). Files can be images, videos, audio, or documents.
3
4
## Capabilities
5
6
### upload
7
8
Upload a file to use in generation requests.
9
10
```typescript { .api }
11
/**
12
* Upload file asynchronously
13
* @param params - File upload parameters
14
* @returns Promise resolving to uploaded file
15
*/
16
function upload(
17
params: UploadFileParameters
18
): Promise<File>;
19
20
interface UploadFileParameters {
21
/** File path (Node.js) or Blob object (browser) */
22
file: string | Blob;
23
/** MIME type (auto-detected from extension if not provided) */
24
mimeType?: string;
25
/** Display name for the file */
26
displayName?: string;
27
}
28
29
interface File {
30
/** File name (unique identifier) */
31
name?: string;
32
/** Display name */
33
displayName?: string;
34
/** MIME type */
35
mimeType?: string;
36
/** File size in bytes */
37
sizeBytes?: string;
38
/** Creation timestamp */
39
createTime?: string;
40
/** Last update timestamp */
41
updateTime?: string;
42
/** Expiration timestamp */
43
expirationTime?: string;
44
/** SHA-256 hash */
45
sha256Hash?: string;
46
/** File URI for use in generation */
47
uri?: string;
48
/** Processing state */
49
state?: FileState;
50
/** Error if processing failed */
51
error?: Status;
52
/** Video metadata (if applicable) */
53
videoMetadata?: VideoMetadata;
54
}
55
```
56
57
**Usage Examples:**
58
59
```typescript
60
import { GoogleGenAI } from '@google/genai';
61
62
const client = new GoogleGenAI({ apiKey: 'YOUR_API_KEY' });
63
64
// Upload image file (Node.js)
65
const imageFile = await client.files.upload({
66
file: './photo.jpg',
67
mimeType: 'image/jpeg',
68
displayName: 'My Photo'
69
});
70
71
console.log('File uploaded:', imageFile.name);
72
console.log('File URI:', imageFile.uri);
73
74
// Wait for processing if needed
75
while (imageFile.state === FileState.PROCESSING) {
76
await new Promise(resolve => setTimeout(resolve, 1000));
77
const updated = await client.files.get({ file: imageFile.name! });
78
if (updated.state === FileState.ACTIVE) {
79
console.log('File ready');
80
break;
81
}
82
}
83
84
// Use in generation
85
const response = await client.models.generateContent({
86
model: 'gemini-2.0-flash',
87
contents: [
88
{ text: 'Describe this image' },
89
{ fileData: {
90
fileUri: imageFile.uri!,
91
mimeType: 'image/jpeg'
92
}}
93
]
94
});
95
96
// Upload video
97
const videoFile = await client.files.upload({
98
file: './video.mp4',
99
mimeType: 'video/mp4'
100
});
101
102
console.log('Video metadata:', videoFile.videoMetadata);
103
```
104
105
### list
106
107
List uploaded files with pagination.
108
109
```typescript { .api }
110
/**
111
* List uploaded files
112
* @param params - List parameters
113
* @returns Promise resolving to pager of files
114
*/
115
function list(
116
params?: ListFilesParameters
117
): Promise<Pager<File>>;
118
119
interface ListFilesParameters {
120
/** Page size */
121
pageSize?: number;
122
/** Page token for pagination */
123
pageToken?: string;
124
}
125
```
126
127
**Usage Examples:**
128
129
```typescript
130
// List all files
131
const pager = await client.files.list({
132
pageSize: 10
133
});
134
135
for await (const file of pager) {
136
console.log(`File: ${file.displayName}`);
137
console.log(` Name: ${file.name}`);
138
console.log(` MIME: ${file.mimeType}`);
139
console.log(` Size: ${file.sizeBytes} bytes`);
140
console.log(` State: ${file.state}`);
141
console.log(` Expires: ${file.expirationTime}`);
142
}
143
144
// Manual pagination
145
const page1 = await client.files.list({ pageSize: 5 });
146
console.log('First page:', page1.page);
147
148
if (page1.hasNextPage()) {
149
const page2 = await page1.nextPage();
150
console.log('Second page:', page2);
151
}
152
```
153
154
### get
155
156
Get file information by name.
157
158
```typescript { .api }
159
/**
160
* Get file by name
161
* @param params - Get parameters
162
* @returns Promise resolving to file
163
*/
164
function get(
165
params: GetFileParameters
166
): Promise<File>;
167
168
interface GetFileParameters {
169
/** File name */
170
file: string;
171
}
172
```
173
174
**Usage Examples:**
175
176
```typescript
177
// Get file details
178
const file = await client.files.get({
179
file: 'files/abc123'
180
});
181
182
console.log('File:', file);
183
console.log('State:', file.state);
184
console.log('URI:', file.uri);
185
```
186
187
### download
188
189
Download a file (Node.js only).
190
191
```typescript { .api }
192
/**
193
* Download file (Node.js only)
194
* @param params - Download parameters
195
* @returns Promise resolving when download completes
196
*/
197
function download(
198
params: DownloadFileParameters
199
): Promise<void>;
200
201
interface DownloadFileParameters {
202
/** File to download */
203
file: DownloadableFileUnion;
204
/** Destination path */
205
path: string;
206
}
207
208
/** File reference types that can be downloaded */
209
type DownloadableFileUnion = string | File | GeneratedVideo | Video;
210
```
211
212
**Usage Examples:**
213
214
```typescript
215
// Download by file object
216
const file = await client.files.upload({
217
file: './source.pdf',
218
mimeType: 'application/pdf'
219
});
220
221
await client.files.download({
222
file: file,
223
path: './downloaded.pdf'
224
});
225
226
// Download by file name
227
await client.files.download({
228
file: 'files/abc123',
229
path: './document.pdf'
230
});
231
232
// Download generated video
233
const videoOp = await client.models.generateVideos({
234
model: 'veo-2.0-generate-001',
235
prompt: 'A sunset'
236
});
237
238
// Wait for completion
239
const completed = await pollOperation(videoOp.name!);
240
241
if (completed.response?.generatedVideos?.[0]) {
242
await client.files.download({
243
file: completed.response.generatedVideos[0],
244
path: './generated.mp4'
245
});
246
}
247
```
248
249
### delete
250
251
Delete an uploaded file.
252
253
```typescript { .api }
254
/**
255
* Delete file
256
* @param params - Delete parameters
257
* @returns Promise resolving to deletion response
258
*/
259
function delete(
260
params: DeleteFileParameters
261
): Promise<DeleteFileResponse>;
262
263
interface DeleteFileParameters {
264
/** File name */
265
file: string;
266
}
267
268
interface DeleteFileResponse {
269
/** Empty response on success */
270
}
271
```
272
273
**Usage Examples:**
274
275
```typescript
276
// Delete file
277
await client.files.delete({
278
file: 'files/abc123'
279
});
280
281
console.log('File deleted');
282
```
283
284
## Types
285
286
### FileState
287
288
File processing states.
289
290
```typescript { .api }
291
enum FileState {
292
STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',
293
PROCESSING = 'PROCESSING',
294
ACTIVE = 'ACTIVE',
295
FAILED = 'FAILED'
296
}
297
```
298
299
### VideoMetadata
300
301
Video-specific metadata.
302
303
```typescript { .api }
304
interface VideoMetadata {
305
/** Video duration (e.g., '3.5s', '1m30s') */
306
videoDuration?: string;
307
}
308
```
309
310
### Status
311
312
Error information if processing failed.
313
314
```typescript { .api }
315
interface Status {
316
/** Error code */
317
code?: number;
318
/** Error message */
319
message?: string;
320
/** Additional error details */
321
details?: unknown[];
322
}
323
```
324
325
## Complete Examples
326
327
### Upload and Use Image
328
329
```typescript
330
import { GoogleGenAI } from '@google/genai';
331
332
const client = new GoogleGenAI({ apiKey: 'YOUR_API_KEY' });
333
334
// Upload image
335
const imageFile = await client.files.upload({
336
file: './product.jpg',
337
mimeType: 'image/jpeg',
338
displayName: 'Product Image'
339
});
340
341
console.log('Uploaded:', imageFile.name);
342
343
// Use in multiple generations
344
const descriptions = await Promise.all([
345
client.models.generateContent({
346
model: 'gemini-2.0-flash',
347
contents: [
348
{ text: 'Describe this product' },
349
{ fileData: { fileUri: imageFile.uri!, mimeType: 'image/jpeg' }}
350
]
351
}),
352
client.models.generateContent({
353
model: 'gemini-2.0-flash',
354
contents: [
355
{ text: 'List features of this product' },
356
{ fileData: { fileUri: imageFile.uri!, mimeType: 'image/jpeg' }}
357
]
358
}),
359
client.models.generateContent({
360
model: 'gemini-2.0-flash',
361
contents: [
362
{ text: 'Suggest marketing copy for this product' },
363
{ fileData: { fileUri: imageFile.uri!, mimeType: 'image/jpeg' }}
364
]
365
})
366
]);
367
368
console.log('Description:', descriptions[0].text);
369
console.log('Features:', descriptions[1].text);
370
console.log('Marketing:', descriptions[2].text);
371
```
372
373
### Upload and Process Video
374
375
```typescript
376
// Upload video
377
const videoFile = await client.files.upload({
378
file: './video.mp4',
379
mimeType: 'video/mp4',
380
displayName: 'Demo Video'
381
});
382
383
console.log('Video uploaded:', videoFile.name);
384
console.log('Initial state:', videoFile.state);
385
386
// Poll until video is processed
387
let processedFile = videoFile;
388
while (processedFile.state === FileState.PROCESSING) {
389
console.log('Processing video...');
390
await new Promise(resolve => setTimeout(resolve, 5000));
391
392
processedFile = await client.files.get({
393
file: videoFile.name!
394
});
395
}
396
397
if (processedFile.state === FileState.ACTIVE) {
398
console.log('Video ready');
399
console.log('Duration:', processedFile.videoMetadata?.videoDuration);
400
401
// Use in generation
402
const response = await client.models.generateContent({
403
model: 'gemini-2.0-flash',
404
contents: [
405
{ text: 'Summarize what happens in this video' },
406
{ fileData: {
407
fileUri: processedFile.uri!,
408
mimeType: 'video/mp4'
409
}}
410
]
411
});
412
413
console.log('Summary:', response.text);
414
} else if (processedFile.state === FileState.FAILED) {
415
console.error('Video processing failed:', processedFile.error);
416
}
417
```
418
419
### Upload Multiple Files
420
421
```typescript
422
const filePaths = ['./doc1.pdf', './doc2.pdf', './doc3.pdf'];
423
424
// Upload all files in parallel
425
const files = await Promise.all(
426
filePaths.map((path, index) =>
427
client.files.upload({
428
file: path,
429
mimeType: 'application/pdf',
430
displayName: `Document ${index + 1}`
431
})
432
)
433
);
434
435
console.log(`Uploaded ${files.length} files`);
436
437
// Use all in single generation
438
const response = await client.models.generateContent({
439
model: 'gemini-2.0-flash',
440
contents: [
441
{ text: 'Analyze these documents and find common themes' },
442
...files.map(file => ({
443
fileData: {
444
fileUri: file.uri!,
445
mimeType: 'application/pdf'
446
}
447
}))
448
]
449
});
450
451
console.log('Analysis:', response.text);
452
```
453
454
### File Management and Cleanup
455
456
```typescript
457
// List all files
458
const files = await client.files.list();
459
460
const now = new Date();
461
462
for await (const file of files) {
463
console.log(`\nFile: ${file.displayName || file.name}`);
464
console.log(` Size: ${file.sizeBytes} bytes`);
465
console.log(` Created: ${file.createTime}`);
466
console.log(` Expires: ${file.expirationTime}`);
467
468
// Delete files expiring soon
469
if (file.expirationTime) {
470
const expiresAt = new Date(file.expirationTime);
471
const hoursUntilExpiry = (expiresAt.getTime() - now.getTime()) / (1000 * 60 * 60);
472
473
if (hoursUntilExpiry < 1) {
474
console.log(' Deleting (expiring soon)...');
475
await client.files.delete({ file: file.name! });
476
}
477
}
478
}
479
```
480
481
### Browser File Upload
482
483
```typescript
484
// In browser environment
485
import { GoogleGenAI } from '@google/genai/web';
486
487
const client = new GoogleGenAI({ apiKey: 'YOUR_API_KEY' });
488
489
// Handle file input
490
document.getElementById('fileInput')?.addEventListener('change', async (e) => {
491
const input = e.target as HTMLInputElement;
492
const file = input.files?.[0];
493
494
if (file) {
495
// Upload blob
496
const uploadedFile = await client.files.upload({
497
file: file,
498
mimeType: file.type,
499
displayName: file.name
500
});
501
502
console.log('Uploaded:', uploadedFile.name);
503
504
// Use in generation
505
const response = await client.models.generateContent({
506
model: 'gemini-2.0-flash',
507
contents: [
508
{ text: 'Describe this file' },
509
{ fileData: {
510
fileUri: uploadedFile.uri!,
511
mimeType: file.type
512
}}
513
]
514
});
515
516
document.getElementById('result')!.textContent = response.text || '';
517
}
518
});
519
```
520
521
### Error Handling
522
523
```typescript
524
try {
525
const file = await client.files.upload({
526
file: './large-video.mp4',
527
mimeType: 'video/mp4'
528
});
529
530
console.log('Upload successful:', file.name);
531
532
// Check for processing errors
533
let processed = file;
534
let attempts = 0;
535
const maxAttempts = 60; // 5 minutes with 5s intervals
536
537
while (processed.state === FileState.PROCESSING && attempts < maxAttempts) {
538
await new Promise(resolve => setTimeout(resolve, 5000));
539
processed = await client.files.get({ file: file.name! });
540
attempts++;
541
}
542
543
if (processed.state === FileState.FAILED) {
544
console.error('File processing failed:', processed.error);
545
} else if (attempts >= maxAttempts) {
546
console.error('Processing timeout');
547
} else {
548
console.log('File ready:', processed.uri);
549
}
550
} catch (error) {
551
console.error('Upload failed:', error);
552
}
553
```
554
555
### Download Generated Content
556
557
```typescript
558
// Generate image
559
const imageResponse = await client.models.generateImages({
560
model: 'imagen-3.0-generate-002',
561
prompt: 'A beautiful sunset'
562
});
563
564
const imageData = imageResponse.generatedImages?.[0]?.image?.data;
565
566
if (imageData) {
567
// Save base64 image (Node.js)
568
const buffer = Buffer.from(imageData, 'base64');
569
require('fs').writeFileSync('./generated-sunset.png', buffer);
570
console.log('Image saved');
571
}
572
573
// Download video from operation
574
const videoOp = await client.models.generateVideos({
575
model: 'veo-2.0-generate-001',
576
prompt: 'Ocean waves'
577
});
578
579
// Poll until complete
580
const completed = await pollVideoOperation(client, videoOp.name!);
581
582
if (completed.response?.generatedVideos?.[0]?.video) {
583
// Download using files module
584
await client.files.download({
585
file: completed.response.generatedVideos[0].video,
586
path: './generated-ocean.mp4'
587
});
588
589
console.log('Video downloaded');
590
}
591
```
592
593
### Audio File Processing
594
595
```typescript
596
// Upload audio file
597
const audioFile = await client.files.upload({
598
file: './speech.mp3',
599
mimeType: 'audio/mpeg',
600
displayName: 'Speech Recording'
601
});
602
603
// Wait for processing
604
while (audioFile.state === FileState.PROCESSING) {
605
await new Promise(resolve => setTimeout(resolve, 2000));
606
const updated = await client.files.get({ file: audioFile.name! });
607
if (updated.state === FileState.ACTIVE) {
608
break;
609
}
610
}
611
612
// Transcribe and analyze
613
const response = await client.models.generateContent({
614
model: 'gemini-2.0-flash',
615
contents: [
616
{ text: 'Transcribe this audio and summarize the key points' },
617
{ fileData: {
618
fileUri: audioFile.uri!,
619
mimeType: 'audio/mpeg'
620
}}
621
]
622
});
623
624
console.log('Transcription:', response.text);
625
```
626
627
### Document Processing
628
629
```typescript
630
// Upload document
631
const docFile = await client.files.upload({
632
file: './report.pdf',
633
mimeType: 'application/pdf',
634
displayName: 'Annual Report'
635
});
636
637
console.log('Document uploaded:', docFile.name);
638
639
// Extract information
640
const extraction = await client.models.generateContent({
641
model: 'gemini-2.0-flash',
642
contents: [
643
{ text: 'Extract key financial figures from this report' },
644
{ fileData: {
645
fileUri: docFile.uri!,
646
mimeType: 'application/pdf'
647
}}
648
]
649
});
650
651
console.log('Extracted data:', extraction.text);
652
653
// Generate summary
654
const summary = await client.models.generateContent({
655
model: 'gemini-2.0-flash',
656
contents: [
657
{ text: 'Provide a 3-paragraph summary of this report' },
658
{ fileData: {
659
fileUri: docFile.uri!,
660
mimeType: 'application/pdf'
661
}}
662
]
663
});
664
665
console.log('Summary:', summary.text);
666
```
667
668
### File Expiration Management
669
670
```typescript
671
// Upload with awareness of expiration (48 hours default)
672
const file = await client.files.upload({
673
file: './temp-data.json',
674
mimeType: 'application/json'
675
});
676
677
console.log('File expires at:', file.expirationTime);
678
679
// Calculate time until expiration
680
const expiresAt = new Date(file.expirationTime!);
681
const now = new Date();
682
const hoursUntilExpiry = (expiresAt.getTime() - now.getTime()) / (1000 * 60 * 60);
683
684
console.log(`File will expire in ${hoursUntilExpiry.toFixed(1)} hours`);
685
686
// If you need the file longer, re-upload before expiration
687
if (hoursUntilExpiry < 2) {
688
console.log('File expiring soon, re-uploading...');
689
const newFile = await client.files.upload({
690
file: './temp-data.json',
691
mimeType: 'application/json'
692
});
693
console.log('New file:', newFile.name);
694
}
695
```
696