Skip to content

Commit ca1c0ed

Browse files
committed
add support to upload file-like object
1 parent 33ef09f commit ca1c0ed

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

google/generativeai/files.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import logging
2222
from google.generativeai import protos
2323
from itertools import islice
24+
from io import IOBase
2425

2526
from google.generativeai.types import file_types
2627

@@ -32,7 +33,7 @@
3233

3334

3435
def upload_file(
35-
path: str | pathlib.Path | os.PathLike,
36+
path: str | pathlib.Path | os.PathLike | IOBase,
3637
*,
3738
mime_type: str | None = None,
3839
name: str | None = None,
@@ -42,7 +43,7 @@ def upload_file(
4243
"""Calls the API to upload a file using a supported file service.
4344
4445
Args:
45-
path: The path to the file to be uploaded.
46+
path: The path to the file or a file-like object (e.g., BytesIO) to be uploaded.
4647
mime_type: The MIME type of the file. If not provided, it will be
4748
inferred from the file extension.
4849
name: The name of the file in the destination (e.g., 'files/sample-image').
@@ -57,17 +58,22 @@ def upload_file(
5758
"""
5859
client = get_default_file_client()
5960

60-
path = pathlib.Path(os.fspath(path))
61+
if not isinstance(path, IOBase):
62+
path = pathlib.Path(os.fspath(path))
63+
64+
if display_name is None:
65+
display_name = path.name
66+
67+
if mime_type is None:
68+
mime_type, _ = mimetypes.guess_type(path)
6169

6270
if mime_type is None:
63-
mime_type, _ = mimetypes.guess_type(path)
71+
# Guess failed or IOBase, use octet-stream.
72+
mime_type = 'application/octet-stream'
6473

6574
if name is not None and "/" not in name:
6675
name = f"files/{name}"
6776

68-
if display_name is None:
69-
display_name = path.name
70-
7177
response = client.create_file(
7278
path=path, mime_type=mime_type, name=name, display_name=display_name, resumable=resumable
7379
)

0 commit comments

Comments
 (0)