# Archivos y entradas

> Usa tu propia imagen, video o audio en una tarea: súbelo con POST /v1/files y luego pon la URL devuelta en la entrada de la tarea.

Esta guía cubre todo el proceso, desde cargar una imagen de referencia de tu disco hasta completar una tarea. Necesitas una clave de API en `KEROX_API_KEY` y un PNG de hasta 4 MB llamado `frame.png` (archivos más grandes: [Archivos grandes](#presigned)). La entrada que recibe el archivo, como `images` para imágenes de referencia, se indica en la [página de cada modelo](https://kerox.ai/es/docs/models.md).

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

## Sube un archivo y úsalo
`POST /v1/files` con el archivo como campo de formulario `file` devuelve HTTP `201` y un objeto de archivo que ya está `ready`. Pon su `url` en el `input` de la tarea; en este ejemplo, 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);
```


La API devuelve el objeto de archivo, que ya está `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"
}
```


Luego consulta la tarea como en [Inicio rápido](https://kerox.ai/es/docs/quickstart.md#submit). Si la tarea falla con `input_fetch_failed`, no se pudo descargar el archivo: vuelve a subirlo (los archivos se conservan 7 días).

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

## Archivos grandes (hasta 200 MB)
Para archivos de más de 4 MB, la subida se hace en tres pasos: envía el nombre, el tipo y el tamaño exacto del archivo como JSON a `POST /v1/files`; envía los bytes con `PUT` a la URL `upload_url` devuelta (válida durante 15 minutos) con todos los encabezados de `upload_headers`; luego consulta `GET /v1/files/{id}` hasta que `status` sea `ready`. La subida está firmada para los valores `content_type` y `size` que declaraste, así que se rechaza un tamaño o tipo distinto. `upload_headers` incluyas `If-None-Match: *`: una URL de subida funciona una sola vez, y un `PUT` cuando el archivo ya está ahí (o se eliminó) devuelve HTTP `412`.

Cuerpo de la solicitud (JSON):

| Campo | Tipo | Obligatorio | Descripción |
| --- | --- | --- | --- |
| `filename` | string | Sí | El nombre del archivo, de 1 a 200 caracteres |
| `content_type` | string | Sí | Uno de los tipos [indicados a continuación](#retention) |
| `size` | integer | Sí | El tamaño exacto del archivo en bytes, hasta 200 MB |

Para este ejemplo de Qwen, usa un PNG de hasta 10 MB cuyos lados midan entre 384 y 3072 píxeles. Después de que un PUT devuelva HTTP `412`, comprueba el ID del archivo: si el archivo está listo, usa su URL. Si el archivo se eliminó o nunca llegó a estar listo, solicita una nueva subida y haz el PUT a la nueva URL de subida.


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


La respuesta del paso 1 (`upload_url` es una URL firmada larga que aquí se muestra abreviada). Cada subida devuelve este objeto de archivo:


```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 | Descripción |
| --- | --- |
| `id` | ID del archivo (`file_...`) |
| `object` | Siempre `"file"` |
| `filename` | El nombre que enviaste |
| `content_type` | El tipo que enviaste |
| `size` | Tamaño en bytes |
| `status` | `pending` hasta que lleguen los bytes; después, `ready`; `deleted` una vez [eliminado](#delete) o superada la fecha de `expires_at` |
| `url` | La dirección que debes indicar en el campo `input` de una tarea; `null` una vez eliminado el archivo |
| `upload_url` | Solo para subidas prefirmadas: la URL a la que enviar los bytes con `PUT`, válida durante 15 minutos |
| `upload_headers` | Solo para subidas prefirmadas: los encabezados que debes enviar con la solicitud `PUT` (`Content-Type` y `If-None-Match: *`) |
| `expires_at` | Cuándo se elimina el archivo: 7 días después de su creación |

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

## Otras formas de pasar un archivo
Consulta la tabla de parámetros del modelo o su `unified.input_schema` para ver los formatos que acepta cada campo. El campo `images` de todos los modelos Qwen Image y de Wan 2.7 Image / Pro, Wan 3.0 / Prime `first_frame`, `last_frame`, `images`, `videos`, `audios`, `file` y `link`, así como de Seedance `videos` (2.0, Fast, Mini y 2.5), requiere URL HTTPS públicas. Para un archivo local, el ejemplo anterior para archivos grandes lo sube y envía a Qwen el `url` devuelto. Para una imagen pública existente, envía este cuerpo a `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` también acepta imágenes en línea. Este PNG es una muestra de color de 32 × 32. En conjunto, los archivos en línea pueden ocupar hasta 3 MB y la solicitud completa, hasta 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>

## Consultar el estado y el plazo de retención
- Llama a `GET /v1/files/{id}` para consultar una subida con URL prefirmada: `"pending"` hasta que lleguen los bytes y, después, `"ready"`.
- Los archivos subidos se eliminan automáticamente tras **7 días**, o antes [si los eliminas tú](#delete).
- Las subidas aceptan estos tipos de contenido: `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`. Cualquier otro `content_type` devuelve HTTP `400` (`invalid_request`). Cada modelo admite solo algunos de ellos: consulta la `input_schema` del modelo para conocer sus límites de formato y resolución.

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

## Eliminar una subida
`DELETE /v1/files/{id}` elimina un archivo subido de inmediato, tanto del almacenamiento como de la caché de la CDN. No se puede recuperar. Solo la cuenta que lo subió puede eliminarlo; otros ID devuelven HTTP `404` (`not_found`). Si vuelves a eliminarlo, se devuelve el mismo objeto.

Una tarea que siga `processing` con este archivo como entrada puede fallar con `input_fetch_failed` (con reembolso completo). Elimina los archivos de entrada cuando hayan terminado las tareas que los usan.

Tras la eliminación, el enlace anterior ya no sirve el archivo (devuelve un archivo vacío, que se limpia en un plazo de días). Una `PUT` aún en curso, o una posterior al mismo `upload_url`, devuelve HTTP `412`: no es posible volver a publicar el archivo en ese enlace.


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


La respuesta contiene el objeto del archivo tras la eliminación:

```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 | Tras la eliminación |
|---|---|
| `status` | `deleted`. Un archivo cuyo plazo de retención de 7 días ha vencido se muestra igual en `GET /v1/files/{id}` |
| `url` | `null` |
| `expires_at` | Se adelanta al momento de la eliminación |
| `filename`, `content_type`, `size` | Sin cambios |
