MCPcopy Create free account
hub / github.com/firebase/quickstart-js / fileToGenerativePart

Function fileToGenerativePart

ai/ai-react-app/src/utils/fileUtils.ts:11–49  ·  view source on GitHub ↗
(file: File)

Source from the content-addressed store, hash-verified

9 * @throws An error if the file cannot be read or processed.
10 */
11export async function fileToGenerativePart(file: File): Promise<Part> {
12 const base64EncodedDataPromise = new Promise<string>((resolve, reject) => {
13 const reader = new FileReader();
14 reader.onloadend = () => {
15 // The FileReader result includes the Data URL prefix (e.g., "data:image/jpeg;base64,").
16 // We only need the actual base64 data part after the comma.
17 const base64String = reader.result as string;
18 if (base64String && base64String.includes(",")) {
19 resolve(base64String.split(",")[1]);
20 } else {
21 reject(new Error("Invalid file data format received from FileReader."));
22 }
23 };
24 reader.onerror = (errorEvent) => {
25 reject(
26 new Error(
27 `FileReader error: ${errorEvent?.target?.error?.message || "Unknown error"}`,
28 ),
29 );
30 };
31 // Start reading the file
32 reader.readAsDataURL(file);
33 });
34
35 try {
36 const base64EncodedData = await base64EncodedDataPromise;
37 return {
38 inlineData: {
39 data: base64EncodedData,
40 mimeType: file.type,
41 },
42 };
43 } catch (error) {
44 console.error("Error converting file to Generative Part:", error);
45 throw new Error(
46 `Failed to process the file "${file.name}". Please ensure it's a valid file.`,
47 );
48 }
49}

Callers 2

PromptInputFunction · 0.90
ChatViewFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected