---
title: Files API
url: https://platform.claude.com/docs/zh-TW/build-with-claude/files
description: 只需上傳檔案一次，即可在 Messages 請求中透過 file_id 參照檔案，並下載由 skills 或程式碼執行工具建立的輸出。
featureMetadata:
  status: ga
  zdr: not-eligible
  supportedPlatforms:
    Claude API: ga
    Claude Platform on AWS: ga
    Microsoft Foundry:
      availability: ga
      note: 在 [Microsoft Foundry](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-in-microsoft-foundry) 上，Files API 需要 [Hosted on Anthropic 部署](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-in-microsoft-foundry#additional-features-not-supported-when-hosted-on-azure)。
---

Files API 讓您可以上傳並管理檔案以搭配 Claude API 使用，而無需在每次請求時重新上傳內容。這在使用[程式碼執行工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool)提供輸入（例如資料集與文件）並接著下載輸出（例如圖表）時特別有用。除了本指南之外，您也可以[直接探索 API 參考文件](https://platform.claude.com/docs/zh-TW/api/files/upload)。

## 檔案類型支援

在 Messages 請求中參照 `file_id`，在所有支援該檔案類型的模型上皆受支援。[圖片](https://platform.claude.com/docs/zh-TW/build-with-claude/vision)在所有目前的 Claude 模型上皆受支援。關於 [PDF](https://platform.claude.com/docs/zh-TW/build-with-claude/pdf-support) 以及[搭配程式碼執行工具的其他檔案類型](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#compatibility)，請參閱連結頁面以了解模型支援情況。

## Files API 的運作方式

Files API 提供一種「建立一次、多次使用」的檔案處理方式：

* **上傳檔案**至 Anthropic 的安全儲存空間，並取得唯一的 `file_id`
* **下載檔案**，這些檔案由 skills 或程式碼執行工具所建立
* **參照檔案**，在 [Messages](https://platform.claude.com/docs/zh-TW/api/messages/create) 請求中使用 `file_id`，而非重新上傳內容
* **管理您的檔案**，透過列出、擷取與刪除操作

<Warning id="workspace-scoped-access">
  **上傳的檔案可供您的整個工作區存取，而非限定於某個終端使用者、對話或工作階段。** 任何具有工作區存取權的 API 金鑰都可以存取上傳至該工作區的任何檔案。每個服務帳戶，以及每位其組織角色允許 API 存取的使用者，除了您將其加入的任何工作區之外，都可以使用 Default Workspace，因此請將必須保持分離的檔案放在各自的[工作區](https://platform.claude.com/docs/zh-TW/manage-claude/workspaces#api-keys-and-resource-scoping)中，並僅使用限定於該工作區的金鑰來存取它們。切勿接受來自終端使用者或其他不受信任來源的 `file_id` 值：由使用者提供的檔案 ID 會讓您應用程式的某位使用者讀取另一位使用者上傳的內容。請將檔案 ID 視為伺服器端的參照，並在您的應用程式中維護使用者與其檔案之間的對應關係。

  如果您正在 Files API 上建構多租戶應用程式，請為每個租戶建立獨立的[工作區](https://platform.claude.com/docs/zh-TW/manage-claude/workspaces)。工作區是檔案的隔離邊界，因此每個租戶一個工作區可讓每個租戶的資料與其他所有租戶之間獲得嚴格隔離。每個組織最多可擁有 100 個工作區；如果您需要更多，請聯繫您的帳戶團隊。
</Warning>

## 如何使用 Files API

### 上傳檔案

上傳檔案以便在未來的 API 呼叫中參照：

<CodeGroup>
  ```bash cURL
  curl -X POST https://api.anthropic.com/v1/files \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -F "file=@/path/to/document.pdf"
  ```

  ```bash CLI
  ant files upload --file /path/to/document.pdf
  ```

  ```python Python
  uploaded = client.files.upload(
      file=("document.pdf", open("/path/to/document.pdf", "rb"), "application/pdf"),
  )
  file_id = uploaded.id
  print(file_id)
  ```

  ```typescript TypeScript
  const uploaded = await client.files.upload({
    file: await toFile(fs.createReadStream("/path/to/document.pdf"), undefined, {
      type: "application/pdf"
    })
  });
  console.log(uploaded.id);
  ```

  ```csharp C#
  var uploaded = await client.Files.Upload(
      new FileUploadParams
      {
          File = new BinaryContent
          {
              Stream = File.OpenRead("/path/to/document.pdf"),
              FileName = "document.pdf",
              ContentType = new("application/pdf")
          }
      });

  var fileId = uploaded.ID;
  Console.WriteLine(fileId);
  ```

  ```go Go
  f, err := os.Open("/path/to/document.pdf")
  if err != nil {
  	log.Fatal(err)
  }
  defer f.Close()

  response, err := client.Files.Upload(context.Background(),
  	anthropic.FileUploadParams{
  		File: anthropic.File(f, "document.pdf", "application/pdf"),
  	})
  if err != nil {
  	log.Fatal(err)
  }

  fileID := response.ID
  fmt.Println(fileID)
  ```

  ```java Java
  FileMetadata file = client.files().upload(
      FileUploadParams.builder()
          .file(MultipartField.<InputStream>builder()
              .value(Files.newInputStream(Path.of("/path/to/document.pdf")))
              .filename("document.pdf")
              .contentType("application/pdf")
              .build())
          .build()
  );

  String fileId = file.id();
  System.out.println(fileId);
  ```

  ```php PHP
  $file = $client->files->upload(
      file: FileParam::fromResource(fopen('/path/to/document.pdf', 'rb'), contentType: 'application/pdf'),
  );

  $fileId = $file->id;
  echo $fileId;
  ```

  ```ruby Ruby
  file = client.files.upload(
    file: Anthropic::FilePart.new(
      Pathname("/path/to/document.pdf"),
      content_type: "application/pdf"
    )
  )

  file_id = file.id
  puts file_id
  ```
</CodeGroup>

上傳檔案的回應包含：

```json Response
{
  "id": "file_011CNha8iCJcU1wXNR6q4V8w",
  "type": "file",
  "filename": "document.pdf",
  "mime_type": "application/pdf",
  "size_bytes": 1024000,
  "created_at": "2025-01-01T00:00:00Z",
  "downloadable": false,
  "expires_at": null
}
```

對於您上傳的檔案，`downloadable` 為 `false`。只有由 [skills](https://platform.claude.com/docs/zh-TW/build-with-claude/skills-guide) 或[程式碼執行工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool)所建立的檔案才能下載。請參閱[下載檔案](https://platform.claude.com/docs/zh-TW/build-with-claude/files#downloading-a-file)。

### 在訊息中使用檔案

上傳完成後，將上傳回應中的 `id` 作為 `file_id` 傳入以參照該檔案：

<CodeGroup>
  ```bash cURL
  curl -X POST https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "messages": [
        {
          "role": "user",
          "content": [
            {
              "type": "text",
              "text": "Please summarize this document for me."
            },
            {
              "type": "document",
              "source": {
                "type": "file",
                "file_id": "'"$FILE_ID"'"
              }
            }
          ]
        }
      ]
    }'
  ```

  ```bash CLI
  ant messages create <<YAML
  model: claude-opus-5-5
  max_tokens: 1024
  messages:
    - role: user
      content:
        - type: text
          text: Please summarize this document for me.
        - type: document
          source:
            type: file
            file_id: $FILE_ID
  YAML
  ```

  ```python Python
  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      messages=[
          {
              "role": "user",
              "content": [
                  {"type": "text", "text": "Please summarize this document for me."},
                  {
                      "type": "document",
                      "source": {
                          "type": "file",
                          "file_id": file_id,
                      },
                  },
              ],
          }
      ],
  )
  print(response)
  ```

  ```typescript TypeScript
  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    messages: [
      {
        role: "user",
        content: [
          {
            type: "text",
            text: "Please summarize this document for me."
          },
          {
            type: "document",
            source: {
              type: "file",
              file_id: uploaded.id
            }
          }
        ]
      }
    ]
  });

  console.log(response);
  ```

  ```csharp C#
  var response = await client.Messages.Create(
      new MessageCreateParams
      {
          Model = Model.ClaudeOpus5_5,
          MaxTokens = 1024,
          Messages =
          [
              new MessageParam
              {
                  Role = Role.User,
                  Content = new List<ContentBlockParam>
                  {
                      new TextBlockParam { Text = "Please summarize this document for me." },
                      new DocumentBlockParam
                      {
                          Source = new FileDocumentSource { FileID = fileId }
                      }
                  }
              }
          ]
      });

  Console.WriteLine(response);
  ```

  ```go Go
  msg, err := client.Messages.New(context.Background(),
  	anthropic.MessageNewParams{
  		Model:     anthropic.ModelClaudeOpus5_5,
  		MaxTokens: 1024,
  		Messages: []anthropic.MessageParam{
  			anthropic.NewUserMessage(
  				anthropic.NewTextBlock("Please summarize this document for me."),
  				anthropic.NewDocumentBlock(anthropic.FileDocumentSourceParam{
  					FileID: fileID,
  				}),
  			),
  		},
  	})
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Println(msg)
  ```

  ```java Java
  MessageCreateParams params = MessageCreateParams.builder()
      .model(Model.CLAUDE_OPUS_5_5)
      .maxTokens(1024)
      .addUserMessageOfBlockParams(List.of(
          ContentBlockParam.ofText(TextBlockParam.builder()
              .text("Please summarize this document for me.")
              .build()),
          ContentBlockParam.ofDocument(DocumentBlockParam.builder()
              .fileSource(fileId)
              .build())
      ))
      .build();

  Message message = client.messages().create(params);
  System.out.println(message);
  ```

  ```php PHP
  $response = $client->messages->create(
      maxTokens: 1024,
      messages: [
          [
              'role' => 'user',
              'content' => [
                  ['type' => 'text', 'text' => 'Please summarize this document for me.'],
                  [
                      'type' => 'document',
                      'source' => [
                          'type' => 'file',
                          'fileID' => $fileId,
                      ],
                  ],
              ],
          ],
      ],
      model: 'claude-opus-5-5',
  );

  echo $response;
  ```

  ```ruby Ruby
  response = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 1024,
    messages: [
      {
        role: "user",
        content: [
          { type: "text", text: "Please summarize this document for me." },
          {
            type: "document",
            source: {
              type: "file",
              file_id: file_id
            }
          }
        ]
      }
    ]
  )

  puts response
  ```
</CodeGroup>

### 檔案類型與內容區塊

Files API 支援不同的檔案類型，分別對應不同的內容區塊（content block）類型：

| 檔案類型                                                                                                                             | MIME 類型                                              | 內容區塊類型             | 使用情境         |
| -------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | ------------------ | ------------ |
| PDF                                                                                                                              | `application/pdf`                                    | `document`         | 文字分析、文件處理    |
| 純文字                                                                                                                              | `text/plain`                                         | `document`         | 文字分析、處理      |
| 圖片                                                                                                                               | `image/jpeg`, `image/png`, `image/gif`, `image/webp` | `image`            | 圖片分析、視覺任務    |
| [資料集、其他](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#upload-and-analyze-your-own-files) | 不定                                                   | `container_upload` | 分析資料、建立視覺化圖表 |

#### Document 區塊

對於 PDF 與文字檔案，請使用 `document` 內容區塊：

```json
{
  "type": "document",
  "source": {
    "type": "file",
    "file_id": "file_011CNha8iCJcU1wXNR6q4V8w"
  },
  "title": "Document Title", // Optional
  "context": "Context about the document", // Optional
  "citations": { "enabled": true } // Optional, enables citations
}
```

#### Image 區塊

對於圖片，請使用 `image` 內容區塊：

```json
{
  "type": "image",
  "source": {
    "type": "file",
    "file_id": "file_011CPMxVD3fHLUhvTqtsQA5w"
  }
}
```

#### Container upload 區塊

若要將檔案傳送至[程式碼執行工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#upload-and-analyze-your-own-files)，請使用 `container_upload` 內容區塊：

```json
{
  "type": "container_upload",
  "file_id": "file_011CNha8iCJcU1wXNR6q4V8w"
}
```

### 處理其他檔案格式

對於 `document` 區塊不支援的檔案類型（例如 .docx 與 .xlsx），請將檔案轉換為純文字，並將內容直接包含在您的訊息中。本身已是純文字的檔案，例如 .csv 與 .md 檔案，可以用這種方式讀取，也可以透過 Files API 以明確的 `text/plain` 內容類型上傳。若要分析資料集而非將其作為文字讀取，請使用 `container_upload` 區塊將其上傳供[程式碼執行工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#upload-and-analyze-your-own-files)使用。

以下範例讀取一個文字檔案，並將其內容以純文字傳送：

<CodeGroup>
  ```bash cURL
  # 讀取文字檔案
  # 注意：若檔案含有特殊字元，建議使用 base64 編碼
  TEXT_CONTENT=$(cat document.txt)

  curl https://api.anthropic.com/v1/messages \
    -H "content-type: application/json" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -d @- <<EOF
  {
    "model": "claude-opus-5-5",
    "max_tokens": 1024,
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": "Here's the document content:\n\n${TEXT_CONTENT}\n\nPlease summarize this document."
          }
        ]
      }
    ]
  }
  EOF
  ```

  ```bash CLI
  # 「@./path」參照會將檔案內容直接內嵌至該欄位中。
  ant messages create \
    --model claude-opus-5-5 \
    --max-tokens 1024 \
    --transform 'content.#(type=="text").text' \
    --raw-output <<'YAML'
  messages:
    - role: user
      content:
        - type: text
          text: "Here's the document content:"
        - type: text
          text: "@./document.txt"
        - type: text
          text: "Please summarize this document."
  YAML
  ```

  ```python Python
  client = anthropic.Anthropic()

  # 讀取文字檔案
  with open("document.txt") as f:
      text_content = f.read()

  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      messages=[
          {
              "role": "user",
              "content": [
                  {
                      "type": "text",
                      "text": f"Here's the document content:\n\n{text_content}\n\nPlease summarize this document.",
                  }
              ],
          }
      ],
  )

  for block in response.content:
      if block.type == "text":
          print(block.text)
  ```

  ```typescript TypeScript
  import fs from "node:fs/promises";
  // ...
  const client = new Anthropic();

  // 讀取文字檔案
  const textContent = await fs.readFile("document.txt", "utf-8");

  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    messages: [
      {
        role: "user",
        content: [
          {
            type: "text",
            text: `Here's the document content:\n\n${textContent}\n\nPlease summarize this document.`
          }
        ]
      }
    ]
  });

  const textBlock = response.content.find(
    (block): block is Anthropic.TextBlock => block.type === "text"
  );
  console.log(textBlock?.text);
  ```

  ```csharp C#
  AnthropicClient client = new();

  // 讀取文字檔案
  string textContent = await File.ReadAllTextAsync("document.txt");

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      Messages = [new()
      {
          Role = Role.User,
          Content = $"Here's the document content:\n\n{textContent}\n\nPlease summarize this document."
      }]
  };

  var message = await client.Messages.Create(parameters);
  foreach (var block in message.Content)
  {
      if (block.TryPickText(out var textBlock))
      {
          Console.WriteLine(textBlock.Text);
      }
  }
  ```

  ```go Go
  client := anthropic.NewClient()

  // 讀取文字檔案
  textContent, err := os.ReadFile("document.txt")
  if err != nil {
  	log.Fatal(err)
  }

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock(
  			fmt.Sprintf("Here's the document content:\n\n%s\n\nPlease summarize this document.", string(textContent)),
  		)),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  for _, block := range response.Content {
  	if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {
  		fmt.Println(textBlock.Text)
  	}
  }
  ```

  ```java Java
  AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  // 讀取文字檔案
  String textContent = Files.readString(Path.of("document.txt"));

  MessageCreateParams params = MessageCreateParams.builder()
      .model(Model.CLAUDE_OPUS_5_5)
      .maxTokens(1024L)
      .addUserMessage("Here's the document content:\n\n" + textContent + "\n\nPlease summarize this document.")
      .build();

  Message response = client.messages().create(params);
  response.content().stream()
      .flatMap(block -> block.text().stream())
      .forEach(textBlock -> System.out.println(textBlock.text()));
  ```

  ```php PHP
  $client = new Client();

  // 讀取文字檔案
  $textContent = file_get_contents("document.txt");

  $message = $client->messages->create(
      maxTokens: 1024,
      messages: [
          [
              'role' => 'user',
              'content' => [
                  [
                      'type' => 'text',
                      'text' => "Here's the document content:\n\n{$textContent}\n\nPlease summarize this document."
                  ]
              ]
          ]
      ],
      model: 'claude-opus-5-5',
  );

  foreach ($message->content as $block) {
      if ($block->type === 'text') {
          echo $block->text, PHP_EOL;
      }
  }
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  # 讀取文字檔案
  text_content = File.read("document.txt")

  message = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 1024,
    messages: [
      {
        role: "user",
        content: [
          {
            type: "text",
            text: "Here's the document content:\n\n#{text_content}\n\nPlease summarize this document."
          }
        ]
      }
    ]
  )

  message.content.each do |block|
    puts block.text if block.type == :text
  end
  ```
</CodeGroup>

<Note>
  對於包含圖片的 .docx 檔案，請先將其轉換為 PDF 格式，然後使用 [PDF 支援](https://platform.claude.com/docs/zh-TW/build-with-claude/pdf-support)以利用內建的圖片解析功能。這樣便可使用來自 PDF 文件的引用。
</Note>

### 管理檔案

#### 列出檔案

擷取您已上傳檔案的清單。此端點採用分頁：每個請求最多回傳 `limit` 個檔案（預設為 20，最多 1,000），而回應中的 `next_page` 游標在作為 `page` 參數傳回時，會擷取下一頁。檔案依最新優先排序。請參閱 [List Files API 參考文件](https://platform.claude.com/docs/zh-TW/api/files/list)。SDK 會回傳第一頁，並提供[自動分頁](https://platform.claude.com/docs/zh-TW/api/overview#pagination)輔助工具。CLI 範例使用 `--max-items` 限制總數：

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/files \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01"
  ```

  ```bash CLI
  ant files list --max-items 10
  ```

  ```python Python
  client = anthropic.Anthropic()
  files = client.files.list()
  print(files)
  ```

  ```typescript TypeScript
  const client = new Anthropic();
  const files = await client.files.list();
  console.log(files);
  ```

  ```csharp C#
  AnthropicClient client = new();

  var files = await client.Files.List();
  Console.WriteLine(files);
  ```

  ```go Go
  client := anthropic.NewClient()

  files, err := client.Files.List(context.TODO(), anthropic.FileListParams{})
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(files)
  ```

  ```java Java
  import com.anthropic.models.files.FileListPage;
  // ...
  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      FileListPage files = client.files().list();
      System.out.println(files);
  }
  ```

  ```php PHP
  $client = new Client();

  $files = $client->files->list();
  echo $files;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  files = client.files.list
  puts files
  ```
</CodeGroup>

若要在單一請求中檢查一組已知的檔案而非逐頁查詢，請以 `ids[]` 查詢參數傳入最多 100 個檔案 ID。`ids[]` 請求一律回傳單一頁面（`next_page` 為 `null`），且任何無法解析為您工作區中檔案的 ID 都會從 `data` 中靜默省略；請將回傳的 ID 與請求的 ID 進行比對以偵測遺漏。`ids[]` 不能與 `page` 或 `limit` 合併使用。

#### 取得檔案中繼資料

擷取特定檔案的相關資訊：

<CodeGroup>
  ```bash cURL
  curl "https://api.anthropic.com/v1/files/$FILE_ID" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01"
  ```

  ```bash CLI
  ant files retrieve-metadata \
    --file-id "$FILE_ID"
  ```

  ```python Python
  file = client.files.retrieve_metadata(file_id)
  print(file)
  ```

  ```typescript TypeScript
  const file = await client.files.retrieveMetadata(uploaded.id);
  console.log(file);
  ```

  ```csharp C#
  var file = await client.Files.RetrieveMetadata(fileId);
  Console.WriteLine(file);
  ```

  ```go Go
  metadata, err := client.Files.GetMetadata(context.TODO(), fileID, anthropic.FileGetMetadataParams{})
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Println(metadata)
  ```

  ```java Java
  FileMetadata metadata = client.files().retrieveMetadata(fileId);

  System.out.println(metadata);
  ```

  ```php PHP
  $file = $client->files->retrieveMetadata($fileId);
  echo $file;
  ```

  ```ruby Ruby
  file = client.files.retrieve_metadata(file_id)
  puts file
  ```
</CodeGroup>

#### 刪除檔案

從您的工作區移除檔案：

<CodeGroup>
  ```bash cURL
  curl -X DELETE "https://api.anthropic.com/v1/files/$FILE_ID" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01"
  ```

  ```bash CLI
  ant files delete \
    --file-id "$FILE_ID"
  ```

  ```python Python
  client.files.delete(file_id)
  ```

  ```typescript TypeScript
  await client.files.delete(uploaded.id);
  ```

  ```csharp C#
  await client.Files.Delete(fileId);
  ```

  ```go Go
  _, err = client.Files.Delete(context.TODO(), fileID, anthropic.FileDeleteParams{})
  if err != nil {
  	log.Fatal(err)
  }
  ```

  ```java Java
  client.files().delete(fileId);
  ```

  ```php PHP
  $client->files->delete($fileId);
  ```

  ```ruby Ruby
  client.files.delete(file_id)
  ```
</CodeGroup>

### 下載檔案

下載由 [skills](https://platform.claude.com/docs/zh-TW/build-with-claude/skills-guide) 或[程式碼執行工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool)所建立的檔案。您上傳的檔案無法下載。所產生檔案的 `file_id` 會出現在建立該檔案的 Messages 回應中的 [`bash_code_execution_tool_result` 內容區塊](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#retrieve-generated-files)裡：

<CodeGroup>
  ```bash cURL
  curl -X GET "https://api.anthropic.com/v1/files/$FILE_ID/content" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    --output downloaded_file.txt
  ```

  ```bash CLI
  ant files download \
    --file-id "$FILE_ID" \
    --output downloaded_file.txt
  ```

  ```python Python
  file_content = client.files.download(file_id)

  file_content.write_to_file("downloaded_file.txt")
  ```

  ```typescript TypeScript
  const content = await client.files.download(uploaded.id);

  const bytes = Buffer.from(await content.arrayBuffer());
  await fsp.writeFile("downloaded_file.txt", bytes);
  ```

  ```csharp C#
  using var fileContent = await client.Files.Download(fileId);
  await using var source = await fileContent.ReadAsStream();
  await using var destination = File.Create("downloaded_file.txt");
  await source.CopyToAsync(destination);
  ```

  ```go Go
  func downloadFile(client anthropic.Client, fileID string) error {
  	resp, err := client.Files.Download(context.TODO(), fileID, anthropic.FileDownloadParams{})
  	if err != nil {
  		return err
  	}
  	defer resp.Body.Close()

  	out, err := os.Create("downloaded_file.txt")
  	if err != nil {
  		return err
  	}
  	defer out.Close()

  	_, err = io.Copy(out, resp.Body)
  	return err
  }
  ```

  ```java Java
  try (HttpResponse response = client.files().download(fileId)) {
      try (InputStream body = response.body()) {
          Files.copy(body, Path.of("downloaded_file.txt"),
              StandardCopyOption.REPLACE_EXISTING);
      }
  }
  ```

  ```php PHP
  $fileContent = $client->files->download($fileId);

  file_put_contents('downloaded_file.txt', $fileContent);
  ```

  ```ruby Ruby
  file_content = client.files.download(file_id)

  File.binwrite("downloaded_file.txt", file_content.read)
  ```
</CodeGroup>

<Note>
  只有當檔案的中繼資料顯示 `"downloadable": true` 時，該檔案才可下載，由 skills 或程式碼執行工具所建立的檔案即屬此情況。下載您上傳的檔案會回傳 400 錯誤。
</Note>

在 Claude API 上，Claude 透過程式碼執行工具產生的受支援圖片、影片和音訊檔案（包括由技能建立的檔案），在您下載時會附帶已簽署的 C2PA「Content Credentials」（內容憑證）。請參閱[產生之檔案上的 Content Credentials](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#content-credentials-on-generated-files)，以了解憑證包含的內容以及如何驗證。

## 檔案儲存與限制

### 儲存限制

* **檔案大小上限：** 每個檔案 500 MB
* **總儲存空間：** 每個組織 1 TB

### 檔案生命週期

* 檔案限定於其上傳所在的工作區。同一工作區中的任何請求都可以參照它們；切勿接受來自不受信任來源的檔案 ID（請參閱[工作區存取警告](https://platform.claude.com/docs/zh-TW/build-with-claude/files#workspace-scoped-access)）
* 檔案在上傳後無法修改或重新命名。若要變更檔案內容，請上傳新檔案並刪除舊檔案
* 檔案會持續保存，直到您使用 `DELETE /v1/files/{file_id}` 端點刪除它們，或它們到達其 `expires_at` 為止
* 已刪除的檔案無法復原
* 檔案在刪除後不久即無法透過 API 存取，但它們可能仍存在於進行中的 Messages API 呼叫及相關的工具使用中
* 使用者刪除的檔案將依據 Anthropic 的[資料保留政策](https://privacy.claude.com/en/articles/7996866-how-long-do-you-store-my-organization-s-data)進行刪除。關於所有功能的 ZDR 資格，請參閱 [API 與資料保留](https://platform.claude.com/docs/zh-TW/manage-claude/api-and-data-retention)

### 檔案到期

若要讓檔案自動到期，請在上傳時包含 `expires_in_seconds` 表單欄位。其值為介於 3,600（1 小時）與 7,776,000（90 天）之間的整數秒數。所產生的 `expires_at` 時間戳記（RFC 3339）會出現在每個檔案回應中，對於未設定到期時間而上傳的檔案則為 `null`。到期時間在上傳時設定一次，之後無法變更。

當檔案到達其 `expires_at` 時：

* 下載其內容（`GET /v1/files/{file_id}/content`）會回傳 404 錯誤
* 參照該檔案的 Messages 請求會在推論之前失敗
* 其中繼資料（`GET /v1/files/{file_id}`）在最多 30 天內仍可讀取，且 `expires_at` 為過去的時間
* 在該期間內它會持續出現在列出回應中；請將 `expires_at` 與目前時間比較以篩選出已到期的檔案

使用 `DELETE /v1/files/{file_id}` 刪除已到期的檔案會立即移除其中繼資料，而非等待 30 天期間結束。

<Note>
  到期是一項生命週期功能，而非保證刪除的控制機制。在 `expires_at` 之後，檔案內容將無法再透過 API 擷取，並會從您的儲存配額中釋放；其底層內容在永久刪除之前，可能會為了安全審查而在之後保留一段有限的期間，且檔案中繼資料在到期後最多 30 天內仍可見。若要在排定的到期時間之前移除檔案，請使用 `DELETE /v1/files/{file_id}`。
</Note>

### 稽核記錄

如果您的組織已啟用 [Compliance API](https://platform.claude.com/docs/zh-TW/manage-claude/compliance-api)，其 [Activity Feed](https://platform.claude.com/docs/zh-TW/manage-claude/compliance-activity-feed) 會記錄以 Claude API 金鑰或從 Claude Console 進行的 Files API 操作：每次上傳（`POST /v1/files`）、內容下載（`GET /v1/files/{file_id}/content`）與刪除（`DELETE /v1/files/{file_id}`）分別會以 `platform_file_uploaded`、`platform_file_content_downloaded` 或 `platform_file_deleted` 活動的形式出現。列出檔案與擷取檔案中繼資料不會被記錄。在 Compliance API 關閉期間發生的操作不會被記錄，且之後無法復原，因此在您依賴此稽核軌跡之前，請先[設定 Compliance API](https://platform.claude.com/docs/zh-TW/manage-claude/compliance-api-access)。在 [Claude Platform on AWS](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-platform-on-aws#monitoring-and-logging) 上，請改用 AWS CloudTrail 資料事件來稽核檔案操作。

## 從 `files-api-2025-04-14` 遷移

Files API 已結束 beta 階段，不再需要 beta 標頭。從 `files-api-2025-04-14` 遷移是選擇性的：仍傳送該標頭的請求會繼續運作，並繼續回傳 beta 回應結構，因此現有的整合在您變更之前會持續運作。移除該標頭會將這些請求切換為本頁所記載的結構：

|                        | 使用 `files-api-2025-04-14`               | 不使用該標頭                                                        |
| ---------------------- | --------------------------------------- | ------------------------------------------------------------- |
| 列出回應                   | `{ data, has_more, first_id, last_id }` | `{ data, next_page }`；將 `next_page` 作為 `page` 查詢參數傳回          |
| 列出游標                   | `before_id`, `after_id`                 | `page`，或最多 100 個 `ids[]`（`before_id` 與 `after_id` 會回傳 400 錯誤） |
| 檔案物件上的 `expires_at`    | 不回傳                                     | 一律存在；當檔案沒有到期時間時為 `null`                                       |
| 上傳檔案部分的 `Content-Type` | 必填                                      | 選填；省略時會自動偵測類型                                                 |

遷移步驟：

1. **移除 beta 標頭。** 從您的請求中移除 `anthropic-beta: files-api-2025-04-14`。在 SDK 中，請呼叫 `client.files` 而非 `client.beta.files`；繼續使用 `client.beta.files` 僅在[不再傳送該標頭的 SDK 版本](https://platform.claude.com/docs/zh-TW/build-with-claude/files#sdk-beta-namespace)上可行。較早的版本即使沒有 `betas` 引數，也會從 `client.beta.files` 傳送該標頭。
2. **更新分頁。** 將 `after_id`/`before_id` 迴圈替換為 `page`/`next_page` 游標，或使用[管理檔案](https://platform.claude.com/docs/zh-TW/build-with-claude/files#managing-files)中所示的 SDK 自動分頁輔助工具。
3. **讀取 `expires_at`。** 此欄位僅在不使用該標頭時出現；`null` 表示檔案沒有到期時間（請參閱[檔案到期](https://platform.claude.com/docs/zh-TW/build-with-claude/files#file-expiration)）。

### SDK beta 命名空間

自 Python SDK 1.2.0、TypeScript SDK 0.122.0、Go SDK 1.68.0、Java SDK 2.59.0、Ruby SDK 1.67.0 與 C# SDK 12.44.0 起，`client.beta.files` 不再傳送 `files-api-2025-04-14`，並回傳與 `client.files` 相同的結構，但型別名稱帶有 `Beta` 前綴。它接受 `betas` 引數以用於仍處於 beta 階段的 Files 功能，例如在 [Managed Agents](https://platform.claude.com/docs/zh-TW/managed-agents/files) beta 標頭下的 `scope_id` 篩選。較早的 SDK 版本的型別對應 beta 結構；如果您依賴這些型別，請在遷移之前停留在較早的版本。

帶有 `anthropic-beta: managed-agents-2026-04-01` 但不帶 `files-api-2025-04-14` 的請求會收到本頁的結構，並在 `GET /v1/files` 上有一項相容性便利措施：`before_id` 與 `after_id` 仍被接受（不可與 `page` 或 `ids[]` 合併使用），且列出回應除了 `next_page` 之外還包含 `has_more`、`first_id` 與 `last_id`。較新的 Managed Agents beta 版本則收到一般結構。

## 錯誤處理

使用 Files API 時的常見錯誤包括：

* **找不到檔案（404）：** 指定的 `file_id` 不存在，或您沒有存取權限
* **無效的檔案類型（400）：** 檔案類型與內容區塊類型不符（例如在 document 區塊中使用圖片檔案）
* **不可下載（400）：** 您上傳的檔案具有 `"downloadable": false`，無法下載。只有由 skills 或程式碼執行工具所建立的檔案才能下載
* **超出上下文視窗大小（400）：** 檔案大於上下文視窗（context window）大小（例如在 `/v1/messages` 請求中使用 500 MB 的純文字檔案）
* **無效的檔案名稱（400）：** 檔案名稱不符合長度要求（1-255 個字元）或包含禁用字元（`<`、`>`、`:`、`"`、`|`、`?`、`*`、`\`、`/`，或 Unicode 字元 0-31）
* **檔案過大（413）：** 檔案超過 500 MB 限制
* **超出儲存限制（400）：** 您的組織已達到 1 TB 儲存限制

```json Output
{
  "type": "error",
  "error": {
    "type": "not_found_error",
    "message": "File `file_011CNha8iCJcU1wXNR6q4V8w` not found."
  },
  "request_id": "req_011CQFYcrRp7mCHLDsAYT8Qt"
}
```

## 用量與計費

Files API 操作免費：

* 上傳檔案
* 下載檔案
* 列出檔案
* 取得檔案中繼資料
* 刪除檔案

在 Messages 請求中使用的檔案內容以輸入 token 計價。

### 速率限制

與檔案相關的 API 呼叫限制為每分鐘約 500 次請求。若要申請更高的限制，請[聯繫銷售團隊](mailto:sales@anthropic.com)。

## 後續步驟

<CardGroup cols={3}>
  <Card title="PDF 支援" icon="file" href="https://platform.claude.com/docs/zh-TW/build-with-claude/pdf-support">
    使用 Claude 處理 PDF。從您的文件中擷取文字、分析圖表並理解視覺內容。
  </Card>

  <Card title="程式碼執行工具" icon="terminal" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool">
    在沙箱容器中執行 Python 與 bash 程式碼，以分析資料、產生檔案並反覆改進解決方案。
  </Card>

  <Card title="視覺" icon="image" href="https://platform.claude.com/docs/zh-TW/build-with-claude/vision">
    處理並分析視覺輸入，並從圖片產生文字與程式碼。
  </Card>
</CardGroup>
