0
# File Management
1
2
Upload, retrieve, list, download, and delete files for use with Gemini models. The Files API supports images, audio, video, and documents up to 2GB per file.
3
4
## Core Imports
5
6
```java
7
import com.google.genai.Files;
8
import com.google.genai.AsyncFiles;
9
import com.google.genai.Pager;
10
import com.google.genai.types.File;
11
import com.google.genai.types.UploadFileConfig;
12
import com.google.genai.types.GetFileConfig;
13
import com.google.genai.types.DeleteFileConfig;
14
import com.google.genai.types.DownloadFileConfig;
15
import com.google.genai.types.ListFilesConfig;
16
import com.google.genai.types.DeleteFileResponse;
17
import java.util.concurrent.CompletableFuture;
18
```
19
20
## Files Service
21
22
```java { .api }
23
package com.google.genai;
24
25
public final class Files {
26
// Upload methods
27
public File upload(java.io.File file, UploadFileConfig config);
28
public File upload(byte[] bytes, UploadFileConfig config);
29
public File upload(InputStream inputStream, long size, UploadFileConfig config);
30
public File upload(String filePath, UploadFileConfig config);
31
32
// Retrieve and list
33
public File get(String name, GetFileConfig config);
34
public Pager<File> list(ListFilesConfig config);
35
36
// Download methods
37
public void download(String fileName, String downloadPath, DownloadFileConfig config);
38
public void download(Video video, String downloadPath, DownloadFileConfig config);
39
public void download(File file, String downloadPath, DownloadFileConfig config);
40
public void download(GeneratedVideo generatedVideo, String downloadPath, DownloadFileConfig config);
41
42
// Delete
43
public DeleteFileResponse delete(String name, DeleteFileConfig config);
44
}
45
```
46
47
## Async Files Service
48
49
```java { .api }
50
package com.google.genai;
51
52
public final class AsyncFiles {
53
public CompletableFuture<File> upload(java.io.File file, UploadFileConfig config);
54
public CompletableFuture<File> upload(byte[] bytes, UploadFileConfig config);
55
public CompletableFuture<File> upload(InputStream inputStream, long size, UploadFileConfig config);
56
public CompletableFuture<File> upload(String filePath, UploadFileConfig config);
57
58
public CompletableFuture<File> get(String name, GetFileConfig config);
59
public CompletableFuture<AsyncPager<File>> list(ListFilesConfig config);
60
61
public CompletableFuture<Void> download(String fileName, String downloadPath, DownloadFileConfig config);
62
public CompletableFuture<Void> download(Video video, String downloadPath, DownloadFileConfig config);
63
public CompletableFuture<Void> download(File file, String downloadPath, DownloadFileConfig config);
64
public CompletableFuture<Void> download(GeneratedVideo generatedVideo, String downloadPath, DownloadFileConfig config);
65
66
public CompletableFuture<DeleteFileResponse> delete(String name, DeleteFileConfig config);
67
}
68
```
69
70
## File Type
71
72
```java { .api }
73
package com.google.genai.types;
74
75
public final class File {
76
public static Builder builder();
77
78
public Optional<String> name();
79
public Optional<String> displayName();
80
public Optional<String> mimeType();
81
public Optional<String> sizeBytes();
82
public Optional<String> createTime();
83
public Optional<String> updateTime();
84
public Optional<String> expirationTime();
85
public Optional<String> sha256Hash();
86
public Optional<String> uri();
87
public Optional<String> state();
88
public Optional<FileStatus> status();
89
public Optional<VideoMetadata> videoMetadata();
90
}
91
```
92
93
### File Status
94
95
```java { .api }
96
package com.google.genai.types;
97
98
public final class FileStatus {
99
public Optional<Status> error();
100
public Optional<String> state();
101
}
102
```
103
104
### Video Metadata
105
106
```java { .api }
107
package com.google.genai.types;
108
109
public final class VideoMetadata {
110
public Optional<String> videoDuration();
111
}
112
```
113
114
## Upload File Config
115
116
```java { .api }
117
package com.google.genai.types;
118
119
public final class UploadFileConfig {
120
public static Builder builder();
121
122
public Optional<String> mimeType();
123
public Optional<String> displayName();
124
public Optional<HttpOptions> httpOptions();
125
}
126
```
127
128
## Get File Config
129
130
```java { .api }
131
package com.google.genai.types;
132
133
public final class GetFileConfig {
134
public static Builder builder();
135
136
public Optional<HttpOptions> httpOptions();
137
}
138
```
139
140
## List Files Config
141
142
```java { .api }
143
package com.google.genai.types;
144
145
public final class ListFilesConfig {
146
public static Builder builder();
147
148
public Optional<Integer> pageSize();
149
public Optional<String> pageToken();
150
public Optional<HttpOptions> httpOptions();
151
}
152
```
153
154
## Download File Config
155
156
```java { .api }
157
package com.google.genai.types;
158
159
public final class DownloadFileConfig {
160
public static Builder builder();
161
162
public Optional<HttpOptions> httpOptions();
163
}
164
```
165
166
## Delete File Response
167
168
```java { .api }
169
package com.google.genai.types;
170
171
public final class DeleteFileResponse {
172
public Optional<HttpResponse> sdkHttpResponse();
173
}
174
```
175
176
## Upload Files
177
178
### Upload from File Object
179
180
```java
181
import com.google.genai.Client;
182
import com.google.genai.types.File;
183
import com.google.genai.types.UploadFileConfig;
184
import java.io.File as JavaFile;
185
186
Client client = new Client();
187
188
UploadFileConfig config = UploadFileConfig.builder()
189
.mimeType("image/jpeg")
190
.displayName("My Image")
191
.build();
192
193
File file = client.files.upload(
194
new JavaFile("path/to/image.jpg"),
195
config
196
);
197
198
System.out.println("Uploaded file: " + file.name().orElse("N/A"));
199
System.out.println("URI: " + file.uri().orElse("N/A"));
200
```
201
202
### Upload from File Path
203
204
```java
205
File file = client.files.upload(
206
"path/to/document.pdf",
207
UploadFileConfig.builder()
208
.mimeType("application/pdf")
209
.displayName("Research Paper")
210
.build()
211
);
212
```
213
214
### Upload from Bytes
215
216
```java
217
import java.nio.file.Files;
218
import java.nio.file.Paths;
219
220
byte[] imageBytes = Files.readAllBytes(Paths.get("path/to/image.png"));
221
222
File file = client.files.upload(
223
imageBytes,
224
UploadFileConfig.builder()
225
.mimeType("image/png")
226
.displayName("Screenshot")
227
.build()
228
);
229
```
230
231
### Upload from InputStream
232
233
```java
234
import java.io.FileInputStream;
235
import java.io.InputStream;
236
237
try (InputStream inputStream = new FileInputStream("path/to/video.mp4")) {
238
long fileSize = new JavaFile("path/to/video.mp4").length();
239
240
File file = client.files.upload(
241
inputStream,
242
fileSize,
243
UploadFileConfig.builder()
244
.mimeType("video/mp4")
245
.displayName("Demo Video")
246
.build()
247
);
248
249
System.out.println("Uploaded: " + file.name().orElse("N/A"));
250
}
251
```
252
253
### Check Upload Status
254
255
```java
256
File file = client.files.upload("path/to/large-video.mp4", null);
257
258
// For large files, check processing status
259
while (file.state().orElse("").equals("PROCESSING")) {
260
Thread.sleep(5000);
261
file = client.files.get(file.name().get(), null);
262
System.out.println("File state: " + file.state().orElse("N/A"));
263
}
264
265
if (file.state().orElse("").equals("ACTIVE")) {
266
System.out.println("File ready to use");
267
}
268
```
269
270
## Retrieve Files
271
272
### Get File by Name
273
274
```java
275
File file = client.files.get("files/abc123", null);
276
277
System.out.println("Name: " + file.name().orElse("N/A"));
278
System.out.println("Display name: " + file.displayName().orElse("N/A"));
279
System.out.println("MIME type: " + file.mimeType().orElse("N/A"));
280
System.out.println("Size: " + file.sizeBytes().orElse("N/A") + " bytes");
281
System.out.println("State: " + file.state().orElse("N/A"));
282
System.out.println("Created: " + file.createTime().orElse("N/A"));
283
System.out.println("Expires: " + file.expirationTime().orElse("N/A"));
284
```
285
286
### Access Video Metadata
287
288
```java
289
File videoFile = client.files.get("files/video123", null);
290
291
videoFile.videoMetadata().ifPresent(metadata -> {
292
System.out.println("Video duration: " + metadata.videoDuration().orElse("N/A"));
293
});
294
```
295
296
## List Files
297
298
### Basic Listing
299
300
```java
301
import com.google.genai.Pager;
302
303
Pager<File> pager = client.files.list(null);
304
305
for (File file : pager) {
306
System.out.println("File: " + file.displayName().orElse("N/A"));
307
System.out.println(" Name: " + file.name().orElse("N/A"));
308
System.out.println(" Type: " + file.mimeType().orElse("N/A"));
309
System.out.println(" Size: " + file.sizeBytes().orElse("N/A"));
310
System.out.println();
311
}
312
```
313
314
### Paginated Listing
315
316
```java
317
ListFilesConfig config = ListFilesConfig.builder()
318
.pageSize(10)
319
.build();
320
321
Pager<File> pager = client.files.list(config);
322
323
// Get first page
324
ImmutableList<File> firstPage = pager.page();
325
System.out.println("Files in first page: " + firstPage.size());
326
327
// Get next page
328
if (firstPage.size() == 10) {
329
ImmutableList<File> secondPage = pager.nextPage();
330
System.out.println("Files in second page: " + secondPage.size());
331
}
332
```
333
334
### Iterate All Files
335
336
```java
337
Pager<File> pager = client.files.list(ListFilesConfig.builder().pageSize(100).build());
338
339
int count = 0;
340
for (File file : pager) {
341
count++;
342
System.out.println(count + ". " + file.displayName().orElse("N/A"));
343
}
344
System.out.println("Total files: " + count);
345
```
346
347
## Download Files
348
349
### Download by File Name
350
351
```java
352
client.files.download(
353
"files/abc123",
354
"path/to/download/file.jpg",
355
null
356
);
357
358
System.out.println("File downloaded successfully");
359
```
360
361
### Download by File Object
362
363
```java
364
File file = client.files.get("files/abc123", null);
365
366
client.files.download(
367
file,
368
"path/to/download/" + file.displayName().orElse("file"),
369
null
370
);
371
```
372
373
### Download Video
374
375
```java
376
import com.google.genai.types.Video;
377
378
Video video = Video.builder()
379
.videoUri("files/video123")
380
.build();
381
382
client.files.download(
383
video,
384
"path/to/download/video.mp4",
385
null
386
);
387
```
388
389
### Download Generated Video
390
391
```java
392
import com.google.genai.types.GeneratedVideo;
393
394
// Assume you have a generated video from video generation
395
GeneratedVideo generatedVideo = /* ... */;
396
397
client.files.download(
398
generatedVideo,
399
"path/to/download/generated-video.mp4",
400
null
401
);
402
```
403
404
## Delete Files
405
406
### Delete by Name
407
408
```java
409
DeleteFileResponse response = client.files.delete("files/abc123", null);
410
System.out.println("File deleted");
411
```
412
413
### Delete After Use
414
415
```java
416
// Upload file
417
File file = client.files.upload("path/to/temp.jpg", null);
418
419
try {
420
// Use file for generation
421
Content content = Content.fromParts(
422
Part.fromText("Describe this image"),
423
Part.fromUri(file.uri().get(), file.mimeType().get())
424
);
425
426
GenerateContentResponse response = client.models.generateContent(
427
"gemini-2.0-flash",
428
content,
429
null
430
);
431
432
System.out.println(response.text());
433
} finally {
434
// Clean up
435
client.files.delete(file.name().get(), null);
436
System.out.println("Temporary file deleted");
437
}
438
```
439
440
## Use Files with Generation
441
442
### Image File with Generation
443
444
```java
445
// Upload image
446
File imageFile = client.files.upload(
447
"path/to/image.jpg",
448
UploadFileConfig.builder().mimeType("image/jpeg").build()
449
);
450
451
// Use in generation
452
Content content = Content.fromParts(
453
Part.fromText("What's in this image?"),
454
Part.fromFileData(FileData.builder()
455
.fileUri(imageFile.uri().get())
456
.mimeType(imageFile.mimeType().get())
457
.build())
458
);
459
460
GenerateContentResponse response = client.models.generateContent(
461
"gemini-2.0-flash",
462
content,
463
null
464
);
465
466
System.out.println(response.text());
467
```
468
469
### Multiple Files
470
471
```java
472
// Upload multiple files
473
File image1 = client.files.upload("image1.jpg", null);
474
File image2 = client.files.upload("image2.jpg", null);
475
File document = client.files.upload("document.pdf", null);
476
477
// Use all in generation
478
Content content = Content.fromParts(
479
Part.fromText("Compare these images and summarize the document:"),
480
Part.fromUri(image1.uri().get(), image1.mimeType().get()),
481
Part.fromUri(image2.uri().get(), image2.mimeType().get()),
482
Part.fromUri(document.uri().get(), document.mimeType().get())
483
);
484
485
GenerateContentResponse response = client.models.generateContent(
486
"gemini-2.0-flash",
487
content,
488
null
489
);
490
```
491
492
### Audio File
493
494
```java
495
File audioFile = client.files.upload(
496
"audio.mp3",
497
UploadFileConfig.builder()
498
.mimeType("audio/mpeg")
499
.displayName("Interview Recording")
500
.build()
501
);
502
503
Content content = Content.fromParts(
504
Part.fromText("Transcribe and summarize this audio"),
505
Part.fromUri(audioFile.uri().get(), audioFile.mimeType().get())
506
);
507
508
GenerateContentResponse response = client.models.generateContent(
509
"gemini-2.0-flash",
510
content,
511
null
512
);
513
```
514
515
## Async File Operations
516
517
### Async Upload
518
519
```java
520
import java.util.concurrent.CompletableFuture;
521
522
CompletableFuture<File> future = client.async.files.upload(
523
"path/to/file.jpg",
524
UploadFileConfig.builder().mimeType("image/jpeg").build()
525
);
526
527
future.thenAccept(file -> {
528
System.out.println("Uploaded: " + file.name().orElse("N/A"));
529
}).exceptionally(error -> {
530
System.err.println("Upload failed: " + error.getMessage());
531
return null;
532
});
533
```
534
535
### Async List
536
537
```java
538
CompletableFuture<AsyncPager<File>> future = client.async.files.list(null);
539
540
future.thenAccept(pager -> {
541
pager.forEach(file -> {
542
System.out.println("File: " + file.displayName().orElse("N/A"));
543
});
544
});
545
```
546
547
### Async Download
548
549
```java
550
CompletableFuture<Void> future = client.async.files.download(
551
"files/abc123",
552
"path/to/download.jpg",
553
null
554
);
555
556
future.thenRun(() -> {
557
System.out.println("Download complete");
558
});
559
```
560
561
## File Lifecycle
562
563
Files uploaded to the Gemini API are automatically deleted after 48 hours.
564
565
```java
566
File file = client.files.upload("path/to/file.jpg", null);
567
568
// File info includes expiration time
569
file.expirationTime().ifPresent(expiration -> {
570
System.out.println("File will expire at: " + expiration);
571
});
572
573
// File will be automatically deleted after 48 hours
574
// Or manually delete earlier:
575
client.files.delete(file.name().get(), null);
576
```
577
578
## Error Handling
579
580
```java
581
import com.google.genai.errors.GenAiIOException;
582
import com.google.genai.errors.ApiException;
583
584
try {
585
File file = client.files.upload("path/to/large-file.mp4", null);
586
System.out.println("Upload successful");
587
} catch (GenAiIOException e) {
588
System.err.println("I/O error: " + e.getMessage());
589
} catch (ApiException e) {
590
System.err.println("API error: " + e.code() + " - " + e.message());
591
}
592
```
593
594
## Best Practices
595
596
### Check File Size Limits
597
598
```java
599
import java.io.File as JavaFile;
600
601
JavaFile localFile = new JavaFile("path/to/file.mp4");
602
long fileSizeBytes = localFile.length();
603
long maxSize = 2L * 1024 * 1024 * 1024; // 2GB
604
605
if (fileSizeBytes > maxSize) {
606
System.err.println("File too large: " + fileSizeBytes + " bytes");
607
} else {
608
File uploadedFile = client.files.upload(localFile, null);
609
}
610
```
611
612
### Wait for Processing
613
614
```java
615
File file = client.files.upload("large-video.mp4", null);
616
617
// Poll until processing complete
618
int maxAttempts = 60;
619
int attempt = 0;
620
while (attempt < maxAttempts && "PROCESSING".equals(file.state().orElse(""))) {
621
Thread.sleep(5000);
622
file = client.files.get(file.name().get(), null);
623
attempt++;
624
}
625
626
if ("ACTIVE".equals(file.state().orElse(""))) {
627
// File ready to use
628
} else if ("FAILED".equals(file.state().orElse(""))) {
629
file.status().flatMap(FileStatus::error).ifPresent(error -> {
630
System.err.println("Processing failed: " + error);
631
});
632
}
633
```
634
635
### Batch Upload Multiple Files
636
637
```java
638
import java.util.List;
639
import java.util.stream.Collectors;
640
import java.util.concurrent.CompletableFuture;
641
642
List<String> filePaths = List.of(
643
"image1.jpg", "image2.jpg", "image3.jpg"
644
);
645
646
// Upload all files asynchronously
647
List<CompletableFuture<File>> futures = filePaths.stream()
648
.map(path -> client.async.files.upload(path, null))
649
.collect(Collectors.toList());
650
651
// Wait for all uploads
652
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
653
.thenRun(() -> {
654
List<File> files = futures.stream()
655
.map(CompletableFuture::join)
656
.collect(Collectors.toList());
657
658
System.out.println("Uploaded " + files.size() + " files");
659
});
660
```
661