# 文件输入方式

本指南介绍了在向 Gemini API 发出请求时包含图像、音频、视频和文档等媒体文件的不同方式。所有 Gemini API 端点都支持新方法，包括 Batch、Interactions 和 Live API。选择正确的方法取决于文件的大小、数据的存储位置以及计划使用该文件的频率。

将文件作为输入包含的最简单方法是读取本地文件并将其包含在提示中。以下示例演示如何读取本地 PDF 文件。对于此方法，PDF 的大小限制为 50MB。请参阅 [输入法对照表](/docs/file-input-methods#method-comparison) 有关文件输入类型和限制的完整列表。

{% tabs %}
{% tab label="Python" %}
```python
from google import genai
import pathlib
import base64

client = genai.Client()

filepath = pathlib.Path('my_local_file.pdf')

prompt = "Summarize this document"
interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input=[
        {"type": "text", "text": prompt},
        {"type": "document", "data": base64.b64encode(filepath.read_bytes()).decode('utf-8'), "mime_type": "application/pdf"}
    ]
)
print(interaction.output_text)
```
{% /tab %}

{% tab label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";
import * as fs from 'node:fs';

const client = new GoogleGenAI({});
const prompt = "Summarize this document";

async function main() {
    const filePath = 'my_local_file.pdf';

    const interaction = await client.interactions.create({
        model: "gemini-4-hydrogen",
        input: [
            { type: "text", text: prompt },
            {
                type: "document",
                data: fs.readFileSync(filePath).toString("base64"),
                mime_type: "application/pdf"
            }
        ]
    });
    console.log(interaction.output_text);
}

await main();
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.DocumentContent;
import com.google.genai.gaos.models.interactions.DocumentContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

byte[] pdfBytes = Files.readAllBytes(Paths.get("my_local_file.pdf"));
String base64Pdf = Base64.getEncoder().encodeToString(pdfBytes);

String prompt = "Summarize this document";

Content textContent = TextContent.builder().text(prompt).build();
Content docContent =
    DocumentContent.builder()
        .data(base64Pdf)
        .mimeType(DocumentContentMimeType.APPLICATION_PDF)
        .build();

List<Content> contents = Arrays.asList(textContent, docContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-4-hydrogen"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
```
{% /tab %}

{% tab label="Go" %}
```go
package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    pdfBytes, err := os.ReadFile("my_local_file.pdf")
    if err != nil {
        log.Fatal(err)
    }
    base64Pdf := base64.StdEncoding.EncodeToString(pdfBytes)

    prompt := "Summarize this document"

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-4-hydrogen"),
            Input: interactions.NewInteractionsInput([]interactions.Content{
                interactions.NewContent(interactions.TextContent{
                    Text: prompt,
                }),
                interactions.NewContent(interactions.DocumentContent{
                    Data:     genai.Ptr(base64Pdf),
                    MimeType: interactions.DocumentContentMimeTypeApplicationPdf.ToPointer(),
                }),
            }),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }
    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }
}
```
{% /tab %}

{% tab label="REST" %}
```bash
# Encode the local file to base64
B64_CONTENT=$(base64 -w 0 my_local_file.pdf)

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -H "Api-Revision: 2026-05-20" \
  -d '{
    "model": "gemini-4-hydrogen",
    "input": [
      {"type": "text", "text": "Summarize this document"},
      {
        "type": "document",
        "data": "'${B64_CONTENT}'",
        "mime_type": "application/pdf"
      }
    ]
  }'
```
{% /tab %}

{% tab label="CLI" %}
```bash
gemini-api analyze -m gemini-4-hydrogen -i my_local_file.pdf "Summarize this document"
```
{% /tab %}
{% /tabs %}

## 输入法比较  {% #method-comparison %}

下表比较了每种输入方法的文件限制和最佳用例。请注意，文件大小限制可能会有所不同，具体取决于文件类型和模型或用于处理文件的标记生成器。

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
方法
{% /doc-cell %}

{% doc-cell %}
最适合
{% /doc-cell %}

{% doc-cell %}
最大文件大小
{% /doc-cell %}

{% doc-cell %}
坚持
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**内联数据**
{% /doc-cell %}

{% doc-cell %}
快速测试、小文件、实时应用。
{% /doc-cell %}

{% doc-cell %}
100 每个请求或有效负载的 MB（**50 MB 用于 PDF**)
{% /doc-cell %}

{% doc-cell %}
无（随每个请求一起发送）
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**文件API上传**
{% /doc-cell %}

{% doc-cell %}
大文件，多次使用的文件。
{% /doc-cell %}

{% doc-cell %}
2 每个文件 GB，每个项目最多 20 GB
{% /doc-cell %}

{% doc-cell %}
48 小时
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**文件 API GCS URI 注册**
{% /doc-cell %}

{% doc-cell %}
Google Cloud 存储中已有大文件，文件被多次使用。
{% /doc-cell %}

{% doc-cell %}
2 每个文件 GB，没有总体存储限制
{% /doc-cell %}

{% doc-cell %}
无（根据请求获取）。一次注册最多可授予 30 天的访问权限。
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**外部网址**
{% /doc-cell %}

{% doc-cell %}
公共数据或云存储桶（AWS、Azure、GCS）中的数据，无需重新上传。
{% /doc-cell %}

{% doc-cell %}
15 每个文件 MB
{% /doc-cell %}

{% doc-cell %}
无（根据请求获取）
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

## 内联数据  {% #inline-data %}

对于较小的文件（小于 100MB，PDF 小于 50MB），您可以直接在请求负载中传递数据。这是快速测试或处理实时瞬态数据的应用程序的最简单方法。您可以以 Base64 编码字符串的形式提供数据，也可以直接读取本地文件来提供数据。

有关从本地文件读取的示例，请参阅本页开头的示例。

### 从 URL 获取  {% #fetch-from-a-url %}

您还可以从 URL 获取文件，将其转换为字节，并将其包含在输入中。

{% tabs %}
{% tab label="Python" %}
```python
from google import genai
import httpx

client = genai.Client()

doc_url = "https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf"
doc_data = httpx.get(doc_url).content

prompt = "Summarize this document"

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input=[
        {"type": "document", "data": base64.b64encode(doc_data).decode('utf-8'), "mime_type": "application/pdf"},
        {"type": "text", "text": prompt}
    ]
)
print(interaction.output_text)
```
{% /tab %}

{% tab label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({});
const docUrl = 'https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf';
const prompt = "Summarize this document";

async function main() {
    const pdfResp = await fetch(docUrl)
      .then((response) => response.arrayBuffer());

    const interaction = await client.interactions.create({
        model: "gemini-4-hydrogen",
        input: [
            { type: "text", text: prompt },
            {
                type: "document",
                data: Buffer.from(pdfResp).toString("base64"),
                mime_type: "application/pdf"
            }
        ]
    });
    console.log(interaction.output_text);
}

await main();
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.DocumentContent;
import com.google.genai.gaos.models.interactions.DocumentContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

String docUrl = "https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf";
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(docUrl)).build();
byte[] docData = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray()).body();
String base64Pdf = Base64.getEncoder().encodeToString(docData);

String prompt = "Summarize this document";

Content docContent =
    DocumentContent.builder()
        .data(base64Pdf)
        .mimeType(DocumentContentMimeType.APPLICATION_PDF)
        .build();
Content textContent = TextContent.builder().text(prompt).build();

List<Content> contents = Arrays.asList(docContent, textContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-4-hydrogen"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
```
{% /tab %}

{% tab label="Go" %}
```go
package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "io"
    "log"
    "net/http"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    docURL := "https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf"
    resp, err := http.Get(docURL)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()
    docData, err := io.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }
    base64Pdf := base64.StdEncoding.EncodeToString(docData)

    prompt := "Summarize this document"

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-4-hydrogen"),
            Input: interactions.NewInteractionsInput([]interactions.Content{
                interactions.NewContent(interactions.DocumentContent{
                    Data:     genai.Ptr(base64Pdf),
                    MimeType: interactions.DocumentContentMimeTypeApplicationPdf.ToPointer(),
                }),
                interactions.NewContent(interactions.TextContent{
                    Text: prompt,
                }),
            }),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }
    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }
}
```
{% /tab %}

{% tab label="REST" %}
```shell
  DOC_URL="https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf"
  PROMPT="Summarize this document"
  DISPLAY_NAME="base64_pdf"

  # Download the PDF
  wget -O "${DISPLAY_NAME}.pdf" "${DOC_URL}"

  # Check for FreeBSD base64 and set flags accordingly
  if [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
    B64FLAGS="--input"
  else
    B64FLAGS="-w0"
  fi

  # Base64 encode the PDF
  ENCODED_PDF=$(base64 $B64FLAGS "${DISPLAY_NAME}.pdf")

  # Create JSON payload file
  cat <payload.json
{
  "model": "gemini-4-hydrogen",
  "input": [
    {"type": "document", "data": "${ENCODED_PDF}", "mime_type": "application/pdf"},
    {"type": "text", "text": "${PROMPT}"}
  ]
}
EOF

    # Generate content using interactions
    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
        -H "x-goog-api-key: $GEMINI_API_KEY" \
        -H 'Content-Type: application/json' \
        -H "Api-Revision: 2026-05-20" \
        -d @payload.json 2> /dev/null > response.json

    cat response.json
    echo

    jq ".outputs[] | select(.type == \"text\") | .text" response.json
```
{% /tab %}

{% tab label="CLI" %}
```bash
curl -sL -o base64_pdf.pdf "https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf"
gemini-api analyze -m gemini-4-hydrogen -i base64_pdf.pdf "Summarize this document"
```
{% /tab %}
{% /tabs %}

## Gemini File API  {% #file-api %}

文件 API 专为较大文件（最多 2GB）或打算在多个请求中使用的文件而设计。

### 标准文件上传  {% #standard-file-upload %}

将本地文件上传到Gemini API。通过这种方式上传的文件将被临时存储（48 小时）并进行处理，以便模型进行有效检索。

{% tabs %}
{% tab label="Python" %}
```python
from google import genai

client = genai.Client()

doc_file = client.files.upload(file="path/to/your/sample.pdf")
prompt = "Summarize this document"

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input=[
        {"type": "text", "text": prompt},
        {"type": "document", "uri": doc_file.uri, "mime_type": doc_file.mime_type}
    ]
)
print(interaction.output_text)
```
{% /tab %}

{% tab label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({});
const prompt = "Summarize this document";

async function main() {
  const filePath = "path/to/your/sample.pdf";

  const myfile = await client.files.upload({
    file: filePath,
    config: { mimeType: "application/pdf" },
  });

  const interaction = await client.interactions.create({
    model: "gemini-4-hydrogen",
    input: [
        { type: "text", text: prompt },
        { type: "document", uri: myfile.uri, mime_type: myfile.mimeType }
    ]
  });
  console.log(interaction.output_text);
}

await main();
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.DocumentContent;
import com.google.genai.gaos.models.interactions.DocumentContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import com.google.genai.types.File;
import com.google.genai.types.UploadFileConfig;
import java.util.Arrays;
import java.util.List;

Client client = new Client();

File docFile =
    client.files.upload(
        new java.io.File("path/to/your/sample.pdf"),
        UploadFileConfig.builder().mimeType("application/pdf").build());

String prompt = "Summarize this document";

Content textContent = TextContent.builder().text(prompt).build();
Content docContent =
    DocumentContent.builder()
        .uri(docFile.uri().orElse(""))
        .mimeType(DocumentContentMimeType.of(docFile.mimeType().orElse("application/pdf")))
        .build();

List<Content> contents = Arrays.asList(textContent, docContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-4-hydrogen"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
```
{% /tab %}

{% tab label="Go" %}
```go
package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    docFile, err := client.Files.UploadFromPath(ctx, "path/to/your/sample.pdf", &genai.UploadFileConfig{
        MIMEType: "application/pdf",
    })
    if err != nil {
        log.Fatal(err)
    }

    prompt := "Summarize this document"

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-4-hydrogen"),
            Input: interactions.NewInteractionsInput([]interactions.Content{
                interactions.NewContent(interactions.TextContent{
                    Text: prompt,
                }),
                interactions.NewContent(interactions.DocumentContent{
                    URI:      genai.Ptr(docFile.URI),
                    MimeType: interactions.DocumentContentMimeType(docFile.MIMEType).ToPointer(),
                }),
            }),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }
    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }
}
```
{% /tab %}

{% tab label="REST" %}
```shell
FILE_PATH="path/to/sample.pdf"
MIME_TYPE=$(file -b --mime-type "${FILE_PATH}")
NUM_BYTES=$(wc -c < "${FILE_PATH}")
DISPLAY_NAME=DOCUMENT

tmp_header_file=upload-header.tmp

# Initial resumable request defining metadata.
curl "https://generativelanguage.googleapis.com/upload/v1beta/files" \
  -D "${tmp_header_file}" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "X-Goog-Upload-Protocol: resumable" \
  -H "X-Goog-Upload-Command: start" \
  -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \
  -H "Content-Type: application/json" \
  -d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null

upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
rm "${tmp_header_file}"

# Upload the actual bytes.
curl "${upload_url}" \
  -H "Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Offset: 0" \
  -H "X-Goog-Upload-Command: upload, finalize" \
  --data-binary "@${FILE_PATH}" 2> /dev/null > file_info.json

file_uri=$(jq ".file.uri" file_info.json)

# Now use in an interaction
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -H "Api-Revision: 2026-05-20" \
    -d '{
      "model": "gemini-4-hydrogen",
      "input": [
        {"type": "text", "text": "Summarize this document"},
        {"type": "document", "uri": '$file_uri', "mime_type": "'${MIME_TYPE}'"}
      ]
    }'
```
{% /tab %}

{% tab label="CLI" %}
```bash
FILE=$(gemini-api files upload path/to/your/sample.pdf --wait)
gemini-api analyze -m gemini-4-hydrogen -i "$FILE" "Summarize this document"
```
{% /tab %}
{% /tabs %}

### 注册Google Cloud存储文件  {% #registration %}

如果您的数据已在 Google Cloud 存储中，则无需下载并重新上传。您可以直接使用文件 API 进行注册。

1. 格兰特 **服务智能体** 访问每个存储桶

1. 在 Google Cloud 项目中启用 Gemini API。

1. 创建服务智能体：

`gcloud beta services identity create --service=generativelanguage.googleapis.com --project=<your_project>`

1. **授予Gemini API服务智能体权限** 读取您的存储桶。

用户需要分配 `Storage Object Viewer`
[IAM 角色](https://docs.cloud.google.com/storage/docs/access-control/iam-roles#storage.objectViewer)
他们打算使用的特定存储桶上的此服务智能体。

默认情况下，此访问权限不会过期，但可以随时更改。您还可以使用 [Google Cloud 存储 IAM SDK](https://cloud.google.com/iam/docs/write-policy-client-libraries)
授予权限的命令。

1. 验证您的服务

**前提条件**

* 启用 API
* 创建具有适当权限的服务帐户或智能体。

您首先需要验证为具有存储对象查看器权限的服务。如何发生这种情况取决于文件管理代码运行的环境。

**Google Cloud 之外**

如果您的代码在 Google Cloud 外部（例如您的桌面）运行，请按照以下步骤从 Google Cloud 控制台下载帐户凭据：

1. 浏览至 [服务帐户控制台](https://console.cloud.google.com/iam-admin/serviceaccounts)
1. 选择相关服务帐号
1. 选择 **按键** 选项卡并选择 **添加密钥、创建新密钥**
1. 选择 **JSON** 密钥类型，并记下文件下载到您计算机上的位置。

有关更多详细信息，请参阅 Google Cloud 官方文档 [服务帐户密钥管理](https://docs.cloud.google.com/iam/docs/keys-create-delete).

然后使用以下命令进行身份验证。这些命令假设您的服务帐户文件位于当前目录中，名为 `service-account.json`.

{% tabs %}
{% tab label="Python" %}
```python
from google.oauth2.service_account import Credentials

GCS_READ_SCOPES = [
  'https://www.googleapis.com/auth/devstorage.read_only',
  'https://www.googleapis.com/auth/cloud-platform'
]

SERVICE_ACCOUNT_FILE = 'service-account.json'

credentials = Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE,
    scopes=GCS_READ_SCOPES
)
```
{% /tab %}

{% tab label="JavaScript" %}
```javascript
const { GoogleAuth } = require('google-auth-library');

const GCS_READ_SCOPES = [
  'https://www.googleapis.com/auth/devstorage.read_only',
  'https://www.googleapis.com/auth/cloud-platform'
];

const SERVICE_ACCOUNT_FILE = 'service-account.json';

const auth = new GoogleAuth({
  keyFile: SERVICE_ACCOUNT_FILE,
  scopes: GCS_READ_SCOPES
});
```
{% /tab %}

{% tab label="gcloud CLI" %}
```bash
gcloud auth application-default login \
  --client-id-file=service-account.json \
  --scopes='https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/devstorage.read_only'
```

**关于Google Cloud**

如果您直接在 Google Cloud 中运行，例如使用 [云运行功能](https://cloud.google.com/functions) 或一个 [计算引擎实例](https://cloud.google.com/products/compute)，您将拥有隐式凭据，但需要重新进行身份验证才能授予适当的范围。
{% /tab %}

{% tab label="Python" %}
此代码期望该服务在以下环境中运行 [应用程序默认凭据](https://docs.cloud.google.com/docs/authentication/application-default-credentials)
可以自动获取，例如Cloud Run或Compute Engine。

```python

import google.auth

GCS_READ_SCOPES = [
  'https://www.googleapis.com/auth/devstorage.read_only',
  'https://www.googleapis.com/auth/cloud-platform'
  ]

credentials, project = google.auth.default(scopes=GCS_READ_SCOPES)
```
{% /tab %}

{% tab label="JavaScript" %}
此代码期望该服务在以下环境中运行 [应用程序默认凭据](https://docs.cloud.google.com/docs/authentication/application-default-credentials)
可以自动获取，例如Cloud Run或Compute Engine。

```javascript

const { GoogleAuth } = require('google-auth-library');

const auth = new GoogleAuth({
  scopes: [
  'https://www.googleapis.com/auth/devstorage.read_only',
  'https://www.googleapis.com/auth/cloud-platform'
  ]
  });
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.auth.oauth2.GoogleCredentials;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.List;

List<String> gcsReadScopes =
    Arrays.asList(
        "https://www.googleapis.com/auth/devstorage.read_only",
        "https://www.googleapis.com/auth/cloud-platform");

String serviceAccountFile = "service-account.json";

GoogleCredentials credentials =
    GoogleCredentials.fromStream(new FileInputStream(serviceAccountFile))
        .createScoped(gcsReadScopes);
```
{% /tab %}

{% tab label="gcloud CLI" %}
这是一个交互式命令。对于像 Compute Engine 这样的服务，您可以在配置级别将范围附加到正在运行的服务。请参阅 [用户管理的服务文档](https://docs.cloud.google.com/compute/docs/access/create-enable-service-accounts-for-instances#using)
举个例子。

```bash

gcloud auth application-default login   
  --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/devstorage.read_only"
```
{% /tab %}
{% /tabs %}

1. 文件注册（Files API）

使用Files API注册文件并生成可直接在Gemini API中使用的Files API路径。

{% tabs %}
{% tab label="Python" %}
```python
from google import genai

client = genai.Client(credentials=credentials)

registered_gcs_files = client.files.register_files(
    uris=["gs://my_bucket/some_object.pdf", "gs://bucket2/object2.txt"]
)
prompt = "Summarize this file."

for f in registered_gcs_files.files:
  print(f.name)
  interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input=[
      {"type": "text", "text": prompt},
      {"type": "document", "uri": f.uri, "mime_type": f.mime_type}
    ],
  )
  print(interaction.output_text)
```
{% /tab %}

{% tab label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

async function main() {
    const registeredGcsFiles = await ai.files.registerFiles({
        uris: ["gs://my_bucket/some_object.pdf", "gs://bucket2/object2.txt"]
    });

    const prompt = "Summarize this file.";

    for (const file of registeredGcsFiles.files || []) {
        console.log(file.name);
        const interaction = await ai.interactions.create({
            model: "gemini-4-hydrogen",
            input: [
                { type: "text", text: prompt },
                { type: "document", uri: file.uri, mime_type: file.mimeType }
            ]
        });

        console.log(interaction.output_text);
    }
}

await main();
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.auth.oauth2.GoogleCredentials;
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.DocumentContent;
import com.google.genai.gaos.models.interactions.DocumentContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import com.google.genai.types.File;
import com.google.genai.types.RegisterFilesResponse;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

GoogleCredentials credentials =
    GoogleCredentials.fromStream(new FileInputStream("service-account.json"))
        .createScoped(
            Arrays.asList(
                "https://www.googleapis.com/auth/devstorage.read_only",
                "https://www.googleapis.com/auth/cloud-platform"));

Client client = Client.builder().credentials(credentials).build();

RegisterFilesResponse registeredGcsFiles =
    client.files.registerFiles(
        credentials,
        Arrays.asList("gs://my_bucket/some_object.pdf", "gs://bucket2/object2.txt"),
        null);

String prompt = "Summarize this file.";

for (File f : registeredGcsFiles.files().orElse(Collections.emptyList())) {
  System.out.println(f.name().orElse(""));

  Content textContent = TextContent.builder().text(prompt).build();
  Content docContent =
      DocumentContent.builder()
          .uri(f.uri().orElse(""))
          .mimeType(DocumentContentMimeType.of(f.mimeType().orElse("application/pdf")))
          .build();

  CreateModelInteraction params =
      CreateModelInteraction.builder()
          .model(Model.of("gemini-4-hydrogen"))
          .input(InteractionsInput.ofContent(Arrays.asList(textContent, docContent)))
          .build();

  Interaction interaction =
      client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
  System.out.println(interaction.outputText().orElse(""));
}
```
{% /tab %}

{% tab label="Go" %}
```go
package main

import (
    "log"

    "google.golang.org/genai"
)

func main() {
    cc := &genai.ClientConfig{}
    if err := cc.UseDefaultCredentials(); err != nil {
        log.Fatal(err)
    }
    _ = cc.Credentials
}
```
{% /tab %}

{% tab label="REST" %}
```bash
access_token=$(gcloud auth application-default print-access-token)
project_id=$(gcloud config get-value project)
curl -X POST https://generativelanguage.googleapis.com/v1beta/files:register \
    -H 'Content-Type: application/json' \
    -H "Authorization: Bearer ${access_token}" \
    -H "x-goog-user-project: ${project_id}" \
    -d '{"uris": ["gs://bucket/object1", "gs://bucket/object2"]}'
```
{% /tab %}

{% tab label="CLI" %}
```bash
gemini-api files register \
  --uris '["gs://my_bucket/some_object.pdf", "gs://bucket2/object2.txt"]' \
  --access-token "$(gcloud auth application-default print-access-token)" \
  --user-project "$(gcloud config get-value project)"
```
{% /tab %}
{% /tabs %}

## 外部 HTTP/签名 URL  {% #external-urls %}

您可以直接在请求中传递可公开访问的 HTTPS URL 或预签名 URL。 Gemini API 将在处理过程中安全地获取内容。这对于您不想重新上传的文件来说是理想的选择。每个文件最大可达 15 MB。对于较大的文件，请使用 [文件 API](/docs/file-input-methods#file-api).

{% callout type="note" %}
不支持 Gemini 2.0 系列型号
{% /callout %}

{% tabs %}
{% tab label="Python" %}
```python
from google import genai

uri = "https://ontheline.trincoll.edu/images/bookdown/sample-local-pdf.pdf"
prompt = "Summarize this file"

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input=[
        {"type": "document", "uri": uri, "mime_type": "application/pdf"},
        {"type": "text", "text": prompt}
    ]
)
print(interaction.output_text)
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.DocumentContent;
import com.google.genai.gaos.models.interactions.DocumentContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;
import java.util.List;

String uri = "https://ontheline.trincoll.edu/images/bookdown/sample-local-pdf.pdf";
String prompt = "Summarize this file";

Client client = new Client();

Content docContent =
    DocumentContent.builder()
        .uri(uri)
        .mimeType(DocumentContentMimeType.APPLICATION_PDF)
        .build();
Content textContent = TextContent.builder().text(prompt).build();

List<Content> contents = Arrays.asList(docContent, textContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-4-hydrogen"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
```
{% /tab %}

{% tab label="Go" %}
```go
package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    cc := &genai.ClientConfig{}
    if err := cc.UseDefaultCredentials(); err != nil {
        log.Fatal(err)
    }
    client, err := genai.NewClient(ctx, cc)
    if err != nil {
        log.Fatal(err)
    }

    registeredGcsFiles, err := client.Files.RegisterFiles(
        ctx,
        []string{"gs://my_bucket/some_object.pdf", "gs://bucket2/object2.txt"},
        cc.Credentials,
        nil,
    )
    if err != nil {
        log.Fatal(err)
    }

    prompt := "Summarize this file."

    for _, f := range registeredGcsFiles.Files {
        fmt.Println(f.Name)
        res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
            Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
                Model: interactions.Model("gemini-4-hydrogen"),
                Input: interactions.NewInteractionsInput([]interactions.Content{
                    interactions.NewContent(interactions.TextContent{
                        Text: prompt,
                    }),
                    interactions.NewContent(interactions.DocumentContent{
                        URI:      genai.Ptr(f.URI),
                        MimeType: interactions.DocumentContentMimeType(f.MIMEType).ToPointer(),
                    }),
                }),
            }),
        })
        if err != nil {
            log.Fatal(err)
        }
        if res.Interaction.OutputText != nil {
            fmt.Println(*res.Interaction.OutputText)
        }
    }
}
```
{% /tab %}

{% tab label="JavaScript" %}
```javascript
import { GoogleGenAI } from '@google/genai';

const client = new GoogleGenAI({});

const uri = "https://ontheline.trincoll.edu/images/bookdown/sample-local-pdf.pdf";

async function main() {
  const interaction = await client.interactions.create({
    model: 'gemini-4-hydrogen',
    input: [
      { type: "document", uri: uri, mime_type: "application/pdf" },
      { type: "text", text: "summarize this file" }
    ]
  });

  console.log(interaction.output_text);
}

await main();
```
{% /tab %}

{% tab label="REST" %}
```bash
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
      -H 'x-goog-api-key: $GEMINI_API_KEY' \
      -H 'Content-Type: application/json' \
      -H "Api-Revision: 2026-05-20" \
      -d '{
          "model": "gemini-4-hydrogen",
          "input": [
            {"type": "text", "text": "Summarize this pdf"},
            {
              "type": "document",
              "uri": "https://ontheline.trincoll.edu/images/bookdown/sample-local-pdf.pdf",
              "mime_type": "application/pdf"
            }
          ]
        }'
```
{% /tab %}

{% tab label="CLI" %}
```bash
gemini-api generate -m gemini-4-hydrogen --body '{
  "input": [
    {"type": "document", "uri": "https://ontheline.trincoll.edu/images/bookdown/sample-local-pdf.pdf", "mime_type": "application/pdf"},
    {"type": "text", "text": "Summarize this file"}
  ]
}'
```
{% /tab %}
{% /tabs %}

### 无障碍  {% #accessibility %}

验证您提供的网址不会指向需要登录或位于付费专区后面的页面。对于私有数据库，请确保您创建具有正确访问权限和到期时间的签名 URL。

### 安全检查  {% #safety-checks %}

系统对 URL 执行内容审核检查，以确认它们符合安全和政策标准。如果 URL 未通过此检查，您将得到一个 `url_retrieval_status` 的 `URL_RETRIEVAL_STATUS_UNSAFE`.

### 支持的内容类型  {% #supported-content-types %}

此支持的文件类型和限制列表旨在作为初步指导，并不全面。支持的有效类型集可能会发生变化，并且可能会根据所使用的特定模型和分词器版本而有所不同。不支持的类型将导致错误。此外，这些文件类型的内容检索仅支持可公开访问的 URL。

#### 文本文件类型  {% #text-file-types %}

* `text/html`
* `text/css`
* `text/plain`
* `text/xml`
* `text/csv`
* `text/rtf`
* `text/javascript`

#### 应用程序文件类型  {% #application-file-types %}

* `application/json`
* `application/pdf`

#### 图像文件类型  {% #image-file-types %}

* `image/bmp`
* `image/jpeg`
* `image/png`
* `image/webp`

#### 音频文件类型  {% #audio-file-types %}

* `audio/wav`
* `audio/mp3`
* `audio/aiff`
* `audio/aac`
* `audio/ogg`
* `audio/flac`
* `audio/mpeg`
* `audio/m4a`
* `audio/l16`
* `audio/opus`
* `audio/alaw`
* `audio/mulaw`
* `audio/webm`

#### 视频文件类型  {% #video-file-types %}

* `video/mp4`
* `video/mpeg`
* `video/quicktime`
* `video/avi`
* `video/x-flv`
* `video/mpg`
* `video/webm`
* `video/wmv`
* `video/3gpp`

## 最佳实践  {% #best-practices %}

* **选择正确的方法：** 对小型瞬态文件使用内联数据。对于较大或经常使用的文件，请使用文件 API。对已在线托管的数据使用外部 URL。

* **指定 MIME 类型：** 始终为文件数据提供正确的 MIME 类型，以确保正确处理。

* **处理错误：** 在代码中实施错误处理，以管理网络故障、文件访问问题或 API 错误等潜在问题。

## 限制  {% #limitations %}

* 文件大小限制因方法而异（请参阅 [对照表](/docs/file-input-methods#method-comparison)）和文件类型。

* 内联数据会增加请求负载大小。

* 文件 API 上传是临时的，在 48 小时后过期。

* 每个文件的外部 URL 获取限制为 15 MB，并支持特定内容类型。

## 后续步骤  {% #whats-next %}

* 尝试使用以下命令编写您自己的多模态提示 [Google AI Studio](http://aistudio.google.com/).

* 有关在提示中包含文件的信息，请参阅 [愿景](/docs/image-understanding), [音频](/docs/audio), 和 [文件处理](/docs/document-processing)
  指南。
