# Tệp & dữ liệu đầu vào

> Dùng hình ảnh, video hoặc âm thanh của riêng bạn trong một tác vụ: tải lên bằng POST /v1/files, rồi đặt url được trả về vào đầu vào của tác vụ.

Trang này hướng dẫn đưa một ảnh tham chiếu từ ổ đĩa của bạn vào một tác vụ hoàn chỉnh. Bạn cần một khóa API trong `KEROX_API_KEY` và một tệp PNG tối đa 4 MB có tên `frame.png` (tệp lớn hơn: xem [Tệp lớn](#presigned)). [Trang của từng mô hình](https://kerox.ai/vi/docs/models.md) ghi rõ trường đầu vào nhận tệp, chẳng hạn `images` cho ảnh tham chiếu.

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

## Tải tệp lên và sử dụng
`POST /v1/files` với tệp ở trường biểu mẫu `file` trả về HTTP `201` và một đối tượng tệp ở trạng thái `ready` ngay lập tức. Đặt `url` của nó vào `input` của tác vụ, ở đây là `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);
```


Yêu cầu tải lên phản hồi bằng đối tượng tệp, đã ở trạng thái `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"
}
```


Sau đó, lấy thông tin tác vụ như trong [Bắt đầu nhanh](https://kerox.ai/vi/docs/quickstart.md#submit). Nếu tác vụ thất bại và báo lỗi `input_fetch_failed`, nghĩa là hệ thống không thể tải xuống tệp: hãy tải tệp lên lại (tệp được lưu giữ 7 ngày).

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

## Tệp lớn (tối đa 200 MB)
Với tệp lớn hơn 4 MB, tải lên theo ba bước: gửi tên, loại và kích thước chính xác của tệp dưới dạng JSON tới `POST /v1/files`; `PUT` các byte tới `upload_url` được trả về (có hiệu lực trong 15 phút) kèm tất cả header trong `upload_headers`; rồi kiểm tra `GET /v1/files/{id}` cho đến khi `status` là `ready`. Chữ ký của yêu cầu tải lên gắn với `content_type` và `size` mà bạn đã khai báo, nên tệp có kích thước hoặc loại khác sẽ bị từ chối. `upload_headers` bao gồm `If-None-Match: *`: mỗi URL tải lên chỉ dùng được một lần, và `PUT` khi tệp đã có sẵn (hoặc đã bị xóa) sẽ trả về HTTP `412`.

Nội dung yêu cầu (JSON):

| Trường | Kiểu | Bắt buộc | Mô tả |
| --- | --- | --- | --- |
| `filename` | string | Có | Tên tệp, dài từ 1 đến 200 ký tự |
| `content_type` | string | Có | Một trong các loại [được liệt kê bên dưới](#retention) |
| `size` | integer | Có | Kích thước chính xác của tệp tính bằng byte, tối đa 200 MB |

Với ví dụ Qwen này, hãy dùng tệp PNG có mỗi cạnh từ 384 đến 3072 pixel, tối đa 10 MB. Sau khi yêu cầu PUT trả về HTTP `412`, hãy kiểm tra ID tệp: nếu tệp đã sẵn sàng, hãy dùng URL của tệp. Nếu tệp đã bị xóa hoặc không chuyển sang trạng thái sẵn sàng, hãy yêu cầu một lượt tải lên mới rồi gửi yêu cầu PUT đến URL được trả về cho lượt tải lên mới đó.


```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);
```


Phản hồi của bước 1 (`upload_url` là một URL đã ký dài, được rút gọn ở đây). Mỗi lượt tải lên đều trả về đối tượng tệp này:


```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": "*"
  }
}
```


| Trường | Mô tả |
| --- | --- |
| `id` | ID tệp (`file_...`) |
| `object` | Luôn là `"file"` |
| `filename` | Tên bạn đã gửi |
| `content_type` | Loại bạn đã gửi |
| `size` | Kích thước tính bằng byte |
| `status` | `pending` cho đến khi dữ liệu được tải lên xong, sau đó là `ready`; `deleted` khi tệp đã bị [xóa](#delete) hoặc sau thời điểm `expires_at` |
| `url` | URL cần điền vào `input` của tác vụ; `null` khi tệp đã bị xóa |
| `upload_url` | Chỉ có khi tải lên bằng URL ký sẵn: URL để `PUT` dữ liệu; URL này có hiệu lực trong 15 phút |
| `upload_headers` | Chỉ có khi tải lên bằng URL ký sẵn: các header HTTP cần gửi kèm yêu cầu `PUT` (`Content-Type` và `If-None-Match: *`) |
| `expires_at` | Khi tệp bị xóa, 7 ngày sau khi được tạo |

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

## Các cách khác để truyền tệp
Hãy xem bảng tham số của mô hình hoặc `unified.input_schema` của mô hình để biết các định dạng mà mỗi trường chấp nhận. Trường `images` trên tất cả các mô hình Qwen Image, trên Wan 2.7 Image / Pro và Wan 3.0 / Prime `first_frame`, `last_frame`, `images`, `videos`, `audios`, `file` và `link`, cùng với Seedance `videos` (2.0, Fast, Mini và 2.5) yêu cầu URL HTTPS công khai. Với tệp cục bộ, ví dụ về tệp lớn ở trên sẽ tải tệp lên và gửi `url` được trả về tới Qwen. Với hình ảnh công khai có sẵn, hãy gửi phần thân yêu cầu này tới `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` cũng chấp nhận hình ảnh nội tuyến. Ảnh PNG này là một mẫu màu kích thước 32 × 32. Tổng dung lượng các tệp nội tuyến có thể lên tới 3 MB và toàn bộ yêu cầu có thể lên tới 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>

## Kiểm tra trạng thái &#38; thời gian lưu giữ
- Gọi `GET /v1/files/{id}` để kiểm tra một lượt tải lên qua URL ký trước. Kết quả là `"pending"` cho đến khi dữ liệu được tải lên xong, sau đó là `"ready"`.
- Các tệp đã tải lên sẽ tự động bị xóa sau **7 ngày**, hoặc sớm hơn [khi bạn xóa chúng](#delete).
- Tính năng tải lên chấp nhận các loại nội dung sau: `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`. Mọi `content_type` khác đều trả về HTTP `400` (`invalid_request`). Mỗi mô hình chỉ nhận một số loại trong đó. Hãy xem `input_schema` của mô hình để biết giới hạn về định dạng và độ phân giải.

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

## Xóa tệp đã tải lên
`DELETE /v1/files/{id}` xóa ngay lập tức một tệp đã tải lên khỏi bộ lưu trữ và khỏi bộ nhớ đệm CDN. Tệp đã xóa không thể khôi phục. Chỉ tài khoản đã tải tệp lên mới có thể xóa tệp. Các ID khác sẽ trả về HTTP `404` (`not_found`). Nếu xóa lại, bạn sẽ nhận được cùng một đối tượng.

Khi đó, những tác vụ vẫn đang ở trạng thái `processing` và dùng tệp này làm đầu vào có thể thất bại với `input_fetch_failed` (được hoàn tiền đầy đủ). Hãy xóa các tệp đầu vào sau khi các tác vụ sử dụng chúng đã hoàn tất.

Sau khi xóa, liên kết cũ không còn trả về tệp nữa (liên kết sẽ trả về một tệp rỗng, và tệp rỗng này sẽ được dọn dẹp trong vòng vài ngày). Một `PUT` vẫn đang diễn ra, hoặc một yêu cầu tương tự gửi sau đó tới cùng `upload_url`, sẽ trả về HTTP `412`. Tệp không thể xuất hiện lại tại liên kết cũ.


```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
```


Phản hồi là tệp ở trạng thái sau khi xóa:

```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"
}
```

| Trường | Sau khi xóa |
|---|---|
| `status` | `deleted`. Tệp đã quá 7 ngày cũng hiển thị như vậy trong `GET /v1/files/{id}` |
| `url` | `null` |
| `expires_at` | Được cập nhật thành thời điểm xóa |
| `filename`, `content_type`, `size` | Không thay đổi |
