# Arquivos e entradas

> Use sua própria imagem, vídeo ou áudio em uma tarefa: envie com POST /v1/files e coloque a url retornada na entrada da tarefa.

Esta página leva uma imagem de referência do seu disco até uma tarefa concluída. Você precisa de uma chave de API em `KEROX_API_KEY` e de um PNG de até 4 MB chamado `frame.png` (arquivos maiores: [Arquivos grandes](#presigned)). A entrada que recebe o arquivo, como `images` para imagens de referência, está indicada na [página de cada modelo](https://kerox.ai/pt-br/docs/models.md).

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

## Enviar um arquivo e usá-lo
`POST /v1/files` com o arquivo no campo de formulário `file` retorna HTTP `201` e um objeto de arquivo que fica `ready` imediatamente. Coloque a `url` dele no `input` da tarefa, aqui como `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);
```


O envio responde com o objeto de arquivo, já `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"
}
```


Depois, consulte a tarefa como no [Início rápido](https://kerox.ai/pt-br/docs/quickstart.md#submit). Se a tarefa falhar com `input_fetch_failed`, não foi possível baixar o arquivo: envie-o novamente (os arquivos são mantidos por 7 dias).

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

## Arquivos grandes (até 200 MB)
Para arquivos acima de 4 MB, envie em três etapas: mande o nome, o tipo e o tamanho exato do arquivo como JSON para `POST /v1/files`; faça `PUT` dos bytes para a `upload_url` retornada (válida por 15 minutos) com todos os cabeçalhos de `upload_headers`; depois consulte `GET /v1/files/{id}` até que `status` seja `ready`. O envio é assinado para o `content_type` e o `size` que você declarou, então um tamanho ou tipo diferente é recusado. `upload_headers` inclua `If-None-Match: *`: uma URL de envio funciona uma única vez, e um `PUT` quando o arquivo já está lá (ou foi excluído) retorna HTTP `412`.

Corpo da requisição (JSON):

| Campo | Tipo | Obrigatório | Descrição |
| --- | --- | --- | --- |
| `filename` | string | Sim | O nome do arquivo, de 1 a 200 caracteres |
| `content_type` | string | Sim | Um dos tipos [listados abaixo](#retention) |
| `size` | integer | Sim | O tamanho exato do arquivo em bytes, até 200 MB |

Para este exemplo do Qwen, use um PNG com cada lado entre 384 e 3072 pixels, de até 10 MB. Depois que um PUT retornar HTTP `412`, verifique o ID do arquivo: use a URL dele se estiver pronto. Se tiver sido excluído ou nunca tiver ficado pronto, solicite um novo upload e faça o PUT no novo endereço.


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


A resposta da etapa 1 (`upload_url` é uma URL assinada longa, abreviada aqui). Todo upload retorna este objeto de arquivo:


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


| Campo | Descrição |
| --- | --- |
| `id` | ID do arquivo (`file_...`) |
| `object` | Sempre `"file"` |
| `filename` | O nome que você enviou |
| `content_type` | O tipo que você enviou |
| `size` | Tamanho em bytes |
| `status` | `pending` até os bytes chegarem, em seguida `ready`; `deleted` após ser [excluído](#delete) ou depois de `expires_at` |
| `url` | O endereço a ser colocado no `input` de uma tarefa; `null` após a exclusão |
| `upload_url` | Somente upload pré-assinado: endereço para onde fazer o `PUT` dos bytes, válido por 15 minutos |
| `upload_headers` | Somente upload pré-assinado: os cabeçalhos a enviar com o `PUT` (`Content-Type` e `If-None-Match: *`) |
| `expires_at` | Quando o arquivo será excluído: 7 dias após a criação |

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

## Outras formas de fornecer um arquivo
Confira a tabela de parâmetros do modelo ou o `unified.input_schema` do modelo para ver os formatos aceitos por cada campo. O campo `images` em todos os modelos Qwen Image e no Wan 2.7 Image / Pro, Wan 3.0 / Prime `first_frame`, `last_frame`, `images`, `videos`, `audios`, `file` e `link`, e no Seedance `videos` (2.0, Fast, Mini e 2.5) exige URLs HTTPS públicas. Para um arquivo local, o exemplo de arquivo grande acima faz o upload e envia ao Qwen o `url` retornado. Para uma imagem pública já existente, envie este corpo para `POST /v1/tasks`.


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


O Seedream 5.5 `images` também aceita imagens inline. Este PNG é uma amostra de cor de 32 × 32. Juntos, os arquivos inline podem ocupar até 3 MB, e a requisição inteira, até 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>

## Verificação de status e retenção
- Chame `GET /v1/files/{id}` para verificar um upload pré-assinado: `"pending"` até que os bytes cheguem e, depois, `"ready"`.
- Os arquivos enviados são excluídos automaticamente após **7 dias**, ou antes, [quando você os excluir](#delete).
- Os uploads aceitam estes tipos de conteúdo: `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`. Qualquer outro `content_type` retorna HTTP `400` (`invalid_request`). Cada modelo aceita apenas alguns deles: confira o `input_schema` do modelo para ver os limites de formato e resolução.

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

## Exclusão de um upload
`DELETE /v1/files/{id}` exclui imediatamente um arquivo enviado, do armazenamento e do cache da CDN. Ele não pode ser recuperado. Somente a conta que fez o upload pode excluí-lo; outros IDs retornam HTTP `404` (`not_found`). Excluir novamente retorna o mesmo objeto.

Uma tarefa que ainda esteja `processing` com este arquivo como entrada poderá, nesse caso, falhar com `input_fetch_failed` (com reembolso integral). Exclua as entradas depois que as tarefas que as utilizam forem concluídas.

Após a exclusão, o link antigo deixa de servir o arquivo (ele retorna um arquivo vazio, removido em alguns dias). Qualquer `PUT` ainda em andamento, ou posterior para o mesmo `upload_url`, retorna HTTP `412`: o arquivo não pode voltar a ficar disponível nesse link.


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


A resposta é o arquivo após a exclusão:

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

| Campo | Após a exclusão |
|---|---|
| `status` | `deleted`. Um arquivo que já passou dos seus 7 dias aparece da mesma forma em `GET /v1/files/{id}` |
| `url` | `null` |
| `expires_at` | Antecipado para o momento da exclusão |
| `filename`, `content_type`, `size` | Sem alteração |
