# 檔案與輸入

> 在任務中使用你自己的圖片、影片或音訊：先以 POST /v1/files 上傳，再將傳回的 url 放入任務輸入。

本頁說明如何將電腦中的參考圖片用於任務，並取得完成的任務。你需要在 `KEROX_API_KEY` 中設定 API 金鑰，並準備一個不超過 4 MB、名為 `frame.png` 的 PNG 檔案（較大的檔案請見[大型檔案](#presigned)）。哪個輸入欄位接受檔案（例如參考圖片使用 `images`），請見各[模型頁面](https://kerox.ai/zh-hant/docs/models.md)。

<a id="upload"></a>

## 上傳檔案並使用
以表單欄位 `file` 附上檔案呼叫 `POST /v1/files`，會回傳 HTTP `201`，以及當下就已是 `ready` 狀態的檔案物件。將其 `url` 放入任務的 `input`，此處為 `images`。


```bash
# Needs curl and jq, and a PNG up to 4 MB named frame.png.
set -euo pipefail
AUTH="Authorization: Bearer $KEROX_API_KEY"

# 1. Upload: HTTP 201, and the file is ready at once.
FILE_URL=$(curl -sS --fail-with-body -X POST https://api.kerox.ai/v1/files \
  -H "$AUTH" -F "file=@frame.png" | jq -r .url)
echo "Uploaded $FILE_URL"

# 2. Use its url in the task's input.
curl -sS --fail-with-body -X POST https://api.kerox.ai/v1/tasks \
  -H "$AUTH" -H "Content-Type: application/json" \
  -d "$(jq -n --arg url "$FILE_URL" '{
    model: "bytedance/seedream-5.5",
    input: { prompt: "a quiet coastal lighthouse at dusk, in the style of the reference image", images: [$url] }
  }')" | jq '{id, status}'
```
```python
# pip install requests
import os
import requests

headers = {"Authorization": f"Bearer {os.environ['KEROX_API_KEY']}"}

# 1. Upload: HTTP 201, and the file is ready at once.
with open("frame.png", "rb") as fh:
    resp = requests.post(
        "https://api.kerox.ai/v1/files",
        headers=headers,
        files={"file": ("frame.png", fh, "image/png")},
        timeout=60,
    )
resp.raise_for_status()
file_url = resp.json()["url"]
print("Uploaded", file_url)

# 2. Use its url in the task's input.
task = requests.post(
    "https://api.kerox.ai/v1/tasks",
    headers=headers,
    json={
        "model": "bytedance/seedream-5.5",
        "input": {"prompt": "a quiet coastal lighthouse at dusk, in the style of the reference image", "images": [file_url]},
    },
    timeout=60,
)
task.raise_for_status()
print(task.json()["id"], task.json()["status"])
```
```javascript
// Node.js 18 or later: fetch, FormData and Blob are built in.
import fs from 'node:fs/promises';

const headers = { Authorization: `Bearer ${process.env.KEROX_API_KEY}` };

// 1. Upload: HTTP 201, and the file is ready at once.
const form = new FormData();
const bytes = await fs.readFile('frame.png');
form.append('file', new Blob([bytes], { type: 'image/png' }), 'frame.png');
const upload = await fetch('https://api.kerox.ai/v1/files', {
  method: 'POST',
  headers,
  body: form,
});
if (upload.status !== 201) {
  throw new Error(`HTTP ${upload.status}: ${await upload.text()}`);
}
const { url: fileUrl } = await upload.json();
console.log('Uploaded', fileUrl);

// 2. Use its url in the task's input.
const res = await fetch('https://api.kerox.ai/v1/tasks', {
  method: 'POST',
  headers: { ...headers, 'Content-Type': 'application/json' },
  body: JSON.stringify({
    model: 'bytedance/seedream-5.5',
    input: { prompt: 'a quiet coastal lighthouse at dusk, in the style of the reference image', images: [fileUrl] },
  }),
});
const task = await res.json();
if (res.status !== 201) throw new Error(`HTTP ${res.status}: ${task.error.message}`);
console.log(task.id, task.status);
```


上傳後會回傳檔案物件，狀態已是 `ready`：


```json
{
  "id": "file_01JD8XB9D3F5G7H9J1K3M5N7P9",
  "object": "file",
  "filename": "frame.png",
  "content_type": "image/png",
  "size": 68,
  "status": "ready",
  "url": "https://cdn.kerox.ai/u/file_01JD8XB9D3F5G7H9J1K3M5N7P9/frame.png",
  "expires_at": "2026-11-27T08:00:52.215Z"
}
```


接著依照[快速入門](https://kerox.ai/zh-hant/docs/quickstart.md#submit)的方式讀取任務。若任務以 `input_fetch_failed` 失敗，表示無法下載該檔案：請重新上傳（檔案保留 7 天）。

<a id="presigned"></a>

## 大型檔案（最大 200 MB）
超過 4 MB 的檔案分三個步驟上傳：先以 JSON 將檔案名稱、類型與確切大小傳送至 `POST /v1/files`；接著帶上 `upload_headers` 中的所有標頭，以 `PUT` 將檔案位元組上傳至回傳的 `upload_url`（15 分鐘內有效）；最後查詢 `GET /v1/files/{id}`，直到 `status` 為 `ready`。上傳簽章綁定你宣告的 `content_type` 與 `size`，因此大小或類型不同的檔案會被拒絕。`upload_headers`包含 `If-None-Match: *`：上傳 URL 只能使用一次，若檔案已存在（或已刪除）時執行 `PUT`，會回傳 HTTP `412`。

請求主體（JSON）：

| 欄位 | 類型 | 必填 | 說明 |
| --- | --- | --- | --- |
| `filename` | string | 是 | 檔案名稱，1–200 個字元 |
| `content_type` | string | 是 | 支援的類型之一，請參閱[下方列出的類型](#retention) |
| `size` | integer | 是 | 檔案的確切大小（位元組），最大 200 MB |

此 Qwen 範例請使用 PNG 圖片，寬度和高度皆須介於 384 到 3072 像素，檔案大小最大 10 MB。PUT 回傳 HTTP `412` 後，請查詢檔案 ID：若檔案已就緒，即可使用其 URL。若檔案已刪除或始終未就緒，請先發出新的上傳請求，取得新的上傳 URL 後，再 PUT 至該 URL。


```bash
API_ORIGIN=${KEROX_API_ORIGIN:-https://api.kerox.ai}
# Needs curl and jq. The file is frame.png.
set -euo pipefail
AUTH="Authorization: Bearer $KEROX_API_KEY"

# 1. Ask for an upload URL. "size" is the exact size in bytes.
FILE=$(curl -sS --fail-with-body -X POST "$API_ORIGIN/v1/files" \
  -H "$AUTH" -H "Content-Type: application/json" \
  -d "$(jq -n --argjson size "$(wc -c < frame.png | tr -d ' ')" \
    '{filename: "frame.png", content_type: "image/png", size: $size}')")
FILE_ID=$(echo "$FILE" | jq -r .id)
FILE_URL=$(echo "$FILE" | jq -r .url)

# 2. PUT the bytes with every header in upload_headers.
HEADERS=()
while IFS= read -r header; do HEADERS+=(-H "$header"); done \
  < <(echo "$FILE" | jq -r '.upload_headers | to_entries[] | "\(.key): \(.value)"')
curl -sS --fail-with-body -X PUT "$(echo "$FILE" | jq -r .upload_url)" \
  "${HEADERS[@]}" --data-binary @frame.png

# 3. Wait until the file is ready (up to 30 seconds).
for _ in $(seq 30); do
  STATUS=$(curl -sS --fail-with-body "$API_ORIGIN/v1/files/$FILE_ID" \
    -H "$AUTH" | jq -r .status)
  [ "$STATUS" = "ready" ] && break
  sleep 1
done
[ "$STATUS" = "ready" ]

# 4. Submit with the ready HTTPS URL.
curl -fsS -X POST "$API_ORIGIN/v1/tasks" -H "$AUTH" -H "Content-Type: application/json" \
  -d "$(jq -n --arg url "$FILE_URL" '{model:"alibaba/qwen-image-2.0",input:{prompt:"Paint this scene in watercolor",images:[$url]}}')" | jq -er .id
```
```python
# pip install requests
import os
import time
import requests

api = os.environ.get("KEROX_API_ORIGIN", "https://api.kerox.ai")

headers = {"Authorization": f"Bearer {os.environ['KEROX_API_KEY']}"}
with open("frame.png", "rb") as fh:
    data = fh.read()

# 1. Ask for an upload URL. "size" is the exact size in bytes.
resp = requests.post(
    f"{api}/v1/files",
    headers=headers,
    json={"filename": "frame.png", "content_type": "image/png", "size": len(data)},
    timeout=30,
)
resp.raise_for_status()
file_obj = resp.json()

# 2. PUT the bytes with every header in upload_headers.
requests.put(
    file_obj["upload_url"], headers=file_obj["upload_headers"], data=data, timeout=300
).raise_for_status()

# 3. Wait until the file is ready (up to 30 seconds).
for _ in range(30):
    check = requests.get(
        f"{api}/v1/files/{file_obj['id']}", headers=headers, timeout=30
    )
    check.raise_for_status()
    status = check.json()["status"]
    if status == "ready":
        break
    time.sleep(1)
else:
    raise SystemExit("The upload never became ready")

# 4. Submit with the ready HTTPS URL.
task = requests.post(
    f"{api}/v1/tasks", headers=headers, timeout=60,
    json={"model": "alibaba/qwen-image-2.0", "input": {"prompt": "Paint this scene in watercolor", "images": [file_obj["url"]]}},
)
task.raise_for_status()
print(task.json()["id"])
```
```javascript
const api = process.env.KEROX_API_ORIGIN || 'https://api.kerox.ai';
// Node.js 18 or later: fetch is built in.
import fs from 'node:fs/promises';

const headers = { Authorization: `Bearer ${process.env.KEROX_API_KEY}` };
const data = await fs.readFile('frame.png');

// 1. Ask for an upload URL. "size" is the exact size in bytes.
const res = await fetch(`${api}/v1/files`, {
  method: 'POST',
  headers: { ...headers, 'Content-Type': 'application/json' },
  body: JSON.stringify({
    filename: 'frame.png',
    content_type: 'image/png',
    size: data.byteLength,
  }),
});
if (res.status !== 201) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
const fileObj = await res.json();

// 2. PUT the bytes with every header in upload_headers.
const put = await fetch(fileObj.upload_url, {
  method: 'PUT',
  headers: fileObj.upload_headers,
  body: data,
});
if (!put.ok) throw new Error(`Upload failed: HTTP ${put.status}`);

// 3. Wait until the file is ready (up to 30 seconds).
let status = 'pending';
for (let i = 0; i < 30 && status !== 'ready'; i++) {
  const check = await fetch(`${api}/v1/files/${fileObj.id}`, { headers });
  if (!check.ok) throw new Error(`HTTP ${check.status}: ${await check.text()}`);
  status = (await check.json()).status;
  if (status !== 'ready') await new Promise((resolve) => setTimeout(resolve, 1000));
}
if (status !== 'ready') throw new Error('The upload never became ready');

// 4. Submit with the ready HTTPS URL.
const task = await fetch(`${api}/v1/tasks`, {
  method: 'POST',
  headers: { ...headers, 'Content-Type': 'application/json' },
  body: JSON.stringify({
    model: 'alibaba/qwen-image-2.0',
    input: { prompt: 'Paint this scene in watercolor', images: [fileObj.url] },
  }),
});
if (!task.ok) throw new Error(`HTTP ${task.status}: ${await task.text()}`);
console.log((await task.json()).id);
```


步驟 1 的回應（`upload_url` 為簽章 URL，因長度較長，此處已截短）。每次上傳都會回傳以下檔案物件：


```json
{
  "id": "file_01JD8XB2K7M9P3Q5R8S1T4V6W0",
  "object": "file",
  "filename": "frame.png",
  "content_type": "image/png",
  "size": 68,
  "status": "pending",
  "url": "https://cdn.kerox.ai/u/file_01JD8XB2K7M9P3Q5R8S1T4V6W0/frame.png",
  "expires_at": "2026-11-27T08:00:41.437Z",
  "upload_url": "https://…/u/file_01JD8XB2K7M9P3Q5R8S1T4V6W0/frame.png?X-Amz-Signature=…",
  "upload_headers": {
    "content-type": "image/png",
    "if-none-match": "*"
  }
}
```


| 欄位 | 說明 |
| --- | --- |
| `id` | 檔案 ID（`file_...`） |
| `object` | 固定為 `"file"` |
| `filename` | 你傳送的名稱 |
| `content_type` | 你傳送的類型 |
| `size` | 大小（位元組） |
| `status` | 檔案資料接收完畢前為 `pending`，之後為 `ready`；[刪除](#delete)後或超過 `expires_at` 時為 `deleted` |
| `url` | 填入任務的 `input` 欄位時使用的位址；刪除後為 `null` |
| `upload_url` | 僅限預先簽署上傳：以 `PUT` 傳送檔案資料的目標位址，有效期限為 15 分鐘 |
| `upload_headers` | 僅限預先簽署上傳：執行 `PUT` 時要一併傳送的標頭（`Content-Type` 和 `If-None-Match: *`） |
| `expires_at` | 檔案的刪除時間，為建立後 7 天 |

<a id="ways"></a>

## 傳入檔案的其他方式
請查看模型的參數表或其 `unified.input_schema`，了解各欄位接受的格式。下列模型的 `images` 欄位都需要公開的 HTTPS URL：所有 Qwen Image 模型；Wan 2.7 Image / Pro、Wan 3.0 / Prime 的 `first_frame`、`last_frame`、`images`、`videos`、`audios`、`file` 和 `link`；以及 Seedance 的 `videos`（2.0、Fast、Mini 與 2.5）。若是本機檔案，可依照上方的大型檔案範例上傳，再將回傳的 `url` 提交給 Qwen。若是現有的公開圖片，請將以下內容傳送到 `POST /v1/tasks`。


```json
{
  "model": "alibaba/qwen-image-2.0",
  "input": {
    "prompt": "Paint this scene in watercolor",
    "images": [
      "https://kerox.ai/icon-512.png"
    ]
  }
}
```


Seedream 5.5 `images` 也接受內嵌圖片。這張 PNG 是 32 × 32 的色票。所有內嵌檔案合計最多 3 MB，整個請求最多 4 MB。


```json
{
  "model": "bytedance/seedream-5.5",
  "input": {
    "prompt": "Paint this scene in watercolor",
    "images": [
      "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAKklEQVR4nGPgSa+lKWIYtWDUglELRi0YtWDUglELRi0YtWDUglELhooFAJ0VwC5Gic1rAAAAAElFTkSuQmCC"
    ]
  }
}
```


<a id="retention"></a>

## 查看狀態與保留期限
- 呼叫 `GET /v1/files/{id}` 可查看預先簽署上傳的狀態：檔案資料接收完畢前為 `"pending"`，之後為 `"ready"`。
- 上傳的檔案會在 **7 天**後自動刪除；你也可以在期限前[自行刪除](#delete)。
- 上傳接受以下內容類型：`image/jpeg`、`image/jpg`、`image/png`、`image/webp`、`image/bmp`、`image/tiff`、`image/gif`、`image/avif`、`image/heic`、`image/heif`、`video/mp4`、`video/quicktime`、`video/webm`、`audio/wav`、`audio/x-wav`、`audio/wave`、`audio/vnd.wave`、`audio/mpeg`、`audio/mp4`。其他任何 `content_type` 都會回傳 HTTP `400`（`invalid_request`）。每個模型只接受其中部分類型：請查看該模型的 `input_schema`，了解其格式與解析度限制。

<a id="delete"></a>

## 刪除上傳的檔案
`DELETE /v1/files/{id}` 會立即刪除已上傳的檔案，同時從儲存空間與 CDN 快取中移除，且無法復原。只有上傳該檔案的帳號可以刪除；其他 ID 會回傳 HTTP `404`（`not_found`）。再次刪除會回傳相同的物件。

若仍處於 `processing` 狀態的任務以此檔案作為輸入，該任務之後可能會失敗並回傳 `input_fetch_failed`（全額退款）。請等使用這些輸入的任務完成後再刪除檔案。

刪除後，舊連結將不再提供該檔案（會回傳空檔案，並於數天內清除）。仍在進行中的 `PUT`，或之後針對同一個 `upload_url` 再次發出的同類請求，都會回傳 HTTP `412`：檔案無法再回到原本的連結。


```bash
# FILE_ID is the id POST /v1/files returned.
curl -sS --fail-with-body -X DELETE "https://api.kerox.ai/v1/files/$FILE_ID" \
  -H "Authorization: Bearer $KEROX_API_KEY"
```
```python
# pip install requests
import os
import requests

# FILE_ID is the id POST /v1/files returned.
resp = requests.delete(
    f"https://api.kerox.ai/v1/files/{os.environ['FILE_ID']}",
    headers={"Authorization": f"Bearer {os.environ['KEROX_API_KEY']}"},
    timeout=30,
)
resp.raise_for_status()
print(resp.json()["status"])  # deleted
```
```javascript
// Node.js 18 or later: fetch is built in.
// FILE_ID is the id POST /v1/files returned.
const res = await fetch(`https://api.kerox.ai/v1/files/${process.env.FILE_ID}`, {
  method: 'DELETE',
  headers: { Authorization: `Bearer ${process.env.KEROX_API_KEY}` },
});
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
const fileObj = await res.json();
console.log(fileObj.status); // deleted
```


回應內容為刪除後的檔案：

```json
{
  "id": "file_01JD8XB2Q7M4T8N3K5P6R1S0VA",
  "object": "file",
  "filename": "frame.png",
  "content_type": "image/png",
  "size": 482113,
  "status": "deleted",
  "url": null,
  "expires_at": "2026-11-21T09:30:00Z"
}
```

| 欄位 | 刪除後 |
|---|---|
| `status` | `deleted`。檔案超過 7 天保存期限後，在 `GET /v1/files/{id}` 中也會顯示相同的值 |
| `url` | `null` |
| `expires_at` | 提前為刪除當下的時間 |
| `filename`、`content_type`、`size` | 不變 |
