Skip to content

Commit 6c98dcb

Browse files
areebuzairareeb
authored andcommitted
docs(readme): add code snippet for files API
The README file of the Gemini Java SDK did not include a snippet for the files API, so this adds one.
1 parent e3a235e commit 6c98dcb

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

README.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,68 @@ public class GenerateContentWithImageInput {
246246
}
247247
```
248248

249+
##### with text input and files api
250+
You can use the Files API to upload a media file. Always use the Files API when the total request size (including the files, text prompt, system instructions, etc.) is larger than 20 MB.
251+
```java
252+
<your package name>;
253+
254+
import com.google.genai.Client;
255+
import com.google.genai.Pager;
256+
import com.google.genai.types.*;
257+
258+
import java.util.List;
259+
260+
261+
public class Main {
262+
public static void main(String[] args) {
263+
Client client = Client
264+
.builder()
265+
.build();
266+
267+
// Upload a file to gemini servers. It remains in the cloud for 48 hours
268+
File fileToUpload = client.files.upload(
269+
"gs://path/to/document.pdf/",
270+
UploadFileConfig.builder().displayName("Document.pdf").mimeType("application/pdf").build()
271+
);
272+
273+
String name = fileToUpload.name().orElse("");
274+
String uri = fileToUpload.uri().orElse("");
275+
String mimeType = fileToUpload.mimeType().orElse("");
276+
277+
// Fetch file metadata using its name
278+
System.out.println("Uploaded File: " + name);
279+
File myFile = client.files.get(name, null);
280+
System.out.println(myFile.toJson());
281+
282+
// List all uploaded files:
283+
Pager<File> allFiles = client.files.list(ListFilesConfig.builder().build());
284+
System.out.println("All uploaded files: ");
285+
while (allFiles.iterator().hasNext()) {
286+
File file = allFiles.iterator().next();
287+
System.out.println(file.toJson());
288+
}
289+
290+
// Generate content with uploaded file
291+
String prompt = "Summarize this file please.";
292+
Part promptPart = Part.fromText(prompt);
293+
Part contentPart = Part.fromUri(uri, mimeType);
294+
Content content = Content.builder()
295+
.parts(List.of(promptPart, contentPart))
296+
.build();
297+
298+
GenerateContentResponse response =
299+
client.models.generateContent(
300+
"gemini-2.5-flash",
301+
content,
302+
null);
303+
System.out.println(response.text());
304+
305+
// Delete file from cloud by name
306+
client.files.delete(name, null);
307+
}
308+
}
309+
```
310+
249311
##### Generate Content with extra configs
250312
To set configurations like System Instructions and Safety Settings, you can pass
251313
a `GenerateContentConfig` to the `GenerateContent` method.

0 commit comments

Comments
 (0)