跳到主要内容

菜单

  • 媒体
  • 定价
  • 文档
  • 语言:简体中文

    此页面不提供灰色显示的语言版本。

    • English
    • Español
    • Português
    • Français
    • Deutsch
    • Italiano
    • Nederlands
    • Polski
    • 日本語
    • 한국어
    • Bahasa Indonesia
    • Tiếng Việt
    • Türkçe
    • العربية
    • ไทย
    • Български
    • Català
    • Hrvatski
    • Eesti
    • Magyar
    • Latviešu
    • Lietuvių
    • Srpski
    • Slovenčina
    • Slovenščina
    • Українська
    • Čeština
    • Română
    • Svenska
    • Dansk
    • Norsk bokmål
    • Suomi
    • עברית
    • हिन्दी
    • Tagalog
    • Bahasa Melayu
    • Ελληνικά
    • 简体中文
    • 繁體中文

热门工具

快速入门

只需五步,即可使用 FilesOkay API 压缩一个视频。每一步都提供 curl、Node.js 和 Python 版本的调用代码,以及返回的响应。

本页内容

开始之前

  • 一个拥有有效订阅的 FilesOkay 工作区。原因请参阅限制与积分。
  • Node.js 步骤需要 Node.js 20 或更高版本。Python 步骤需要 Python 3.9 或更高版本,以及 requests 包。
  • 一个要压缩的视频。示例中的文件名为 lecture.mp4。

以下步骤会逐步构建一个脚本。脚本以下面的代码开头,它从环境变量 FILESOKAY_KEY 中读取您的密钥:

export FILESOKAY_KEY="filesokay_…"
// quickstart.mjs:使用 `node quickstart.mjs` 运行(需要 Node.js 20 或更高版本)。
import fs from "node:fs";
import https from "node:https";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";

const API = "https://api.filesokay.com/v1";

// 调用 API;请求被拒绝时抛出其错误码。
async function api(method, path, body, headers = {}) {
  const res = await fetch(API + path, {
    method,
    headers: {
      Authorization: `Bearer ${process.env.FILESOKAY_KEY}`,
      "Content-Type": "application/json",
      ...headers,
    },
    body: body && JSON.stringify(body),
  });
  const data = res.status === 204 ? null : await res.json();
  if (!res.ok) throw new Error(`${data.code}: ${data.detail}`);
  return data;
}
# quickstart.py:使用 `python quickstart.py` 运行(需要 Python 3.9 或更高版本,并执行 `pip install requests`)。
import os
import time
import uuid

import requests

API = "https://api.filesokay.com/v1"


def api(method, path, body=None, headers=None):
    """调用 API;请求被拒绝时抛出其错误码。"""
    res = requests.request(
        method,
        API + path,
        json=body,
        headers={"Authorization": f"Bearer {os.environ['FILESOKAY_KEY']}", **(headers or {})},
    )
    data = res.json() if res.content else None
    if not res.ok:
        raise RuntimeError(f"{data['code']}: {data['detail']}")
    return data

1. 创建 API 密钥

在工作区中打开设置,进入 API 密钥,然后选择创建 API 密钥。为密钥命名,并完成身份确认。密钥只显示一次:请将其复制到 FILESOKAY_KEY 中。

2. 上传文件

使用文件名和文件大小发起上传。将文件发送到返回的链接,然后完成上传,系统会在这一步检测文件。

# 使用文件名和文件大小(字节)发起上传。
curl https://api.filesokay.com/v1/uploads \
  -H "Authorization: Bearer $FILESOKAY_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "operation": "video.compress",
    "files": [{ "name": "lecture.mp4", "size": 12417467 }]
  }'

# 将文件发送到其分片链接,即响应中的 files[0].parts[0].url。
curl -X PUT --upload-file lecture.mp4 "$PART_URL"

# 完成上传,系统会检测该文件。
curl -X POST https://api.filesokay.com/v1/uploads/file_3cf0737aefa34b89b7b4443c9467d60c/complete \
  -H "Authorization: Bearer $FILESOKAY_KEY"
const name = "lecture.mp4";
const { size } = fs.statSync(name);

// 使用文件名和文件大小(字节)发起上传。
const { files: [upload] } = await api("POST", "/uploads", {
  operation: "video.compress",
  files: [{ name, size }],
});

// 直接从磁盘将文件发送到其链接。链接自带访问权限,无需密钥。
await new Promise((resolve, reject) => {
  const req = https.request(upload.parts[0].url, {
    method: "PUT",
    headers: { "Content-Length": size },
  });
  req.on("response", (res) => {
    res.resume();
    if (res.statusCode === 200) resolve();
    else reject(new Error(`Upload failed: ${res.statusCode}`));
  });
  req.on("error", reject);
  fs.createReadStream(name).on("error", reject).pipe(req);
});

// 完成上传,系统会检测该文件。
const uploaded = await api("POST", `/uploads/${upload.id}/complete`);
console.log(uploaded.check.state);
name = "lecture.mp4"

# 使用文件名和文件大小(字节)发起上传。
upload = api("POST", "/uploads", {
    "operation": "video.compress",
    "files": [{"name": name, "size": os.path.getsize(name)}],
})["files"][0]

# 直接从磁盘将文件发送到其链接。链接自带访问权限,无需密钥。
with open(name, "rb") as f:
    requests.put(upload["parts"][0]["url"], data=f).raise_for_status()

# 完成上传,系统会检测该文件。
uploaded = api("POST", f"/uploads/{upload['id']}/complete")
print(uploaded["check"]["state"])
响应
{
  "id": "file_3cf0737aefa34b89b7b4443c9467d60c",
  "name": "lecture.mp4",
  "operation": "video.compress",
  "state": "uploaded",
  "size": 12417467,
  "created_at": "2026-12-03T08:59:54Z",
  "uploaded_at": "2026-12-03T09:00:00Z",
  "delete_at": "2026-12-04T09:00:00Z",
  "check": {
    "state": "proceed",
    "kind": "video",
    "type": "mp4",
    "facts": {
      "container": "mp4",
      "protection": "none",
      "attachments": [],
      "duration_ms": 20023,
      "frame_count": 600,
      "audio_tracks": [
        {
          "codec": "aac",
          "channels": 1,
          "sample_rate": 44100
        }
      ],
      "video_tracks": [
        {
          "hdr": "none",
          "codec": "h264",
          "width": 1280,
          "chroma": "420",
          "height": 720,
          "profile": "High",
          "rotation": 0,
          "bit_depth": 8,
          "frame_rate": 30,
          "interlaced": false,
          "variable_frame_rate": false
        }
      ],
      "data_end_bytes": 12417467,
      "subtitle_tracks": []
    },
    "facts_complete": true
  }
}

proceed 表示作业可以使用该文件。5 GB 以内的文件通过一次请求发送。更大的文件如何发送,请参阅上传文件。

3. 启动作业

指定操作和文件。省略的设置会使用默认值,video.compress 的默认值是均衡的质量等级。Idempotency-Key 请求头可确保重试安全:请参阅安全重试。

curl https://api.filesokay.com/v1/jobs \
  -H "Authorization: Bearer $FILESOKAY_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
    "operation": "video.compress",
    "inputs": [{ "file_id": "file_3cf0737aefa34b89b7b4443c9467d60c" }]
  }'
const job = await api(
  "POST",
  "/jobs",
  { operation: "video.compress", inputs: [{ file_id: upload.id }] },
  { "Idempotency-Key": crypto.randomUUID() },
);
console.log(job.id, job.status);
job = api(
    "POST",
    "/jobs",
    {"operation": "video.compress", "inputs": [{"file_id": upload["id"]}]},
    {"Idempotency-Key": str(uuid.uuid4())},
)
print(job["id"], job["status"])
响应
{
  "id": "job_a1c9531eeb00434aba0058796f1ca517",
  "operation": "video.compress",
  "status": "waiting",
  "client_reference": null,
  "settings": {
    "audio": "keep",
    "codec": "same",
    "level": "balanced",
    "method": "quality",
    "frame_rate": "original",
    "resolution": "original",
    "output_format": "same"
  },
  "created_at": "2026-12-03T09:00:12Z",
  "reserved_credits": 2,
  "charged_credits": 0,
  "tasks": [
    {
      "id": "task_4256d03a73a741afa1821546a2bcba98",
      "status": "waiting",
      "progress": 0,
      "reserved_credits": 2,
      "inputs": [
        {
          "file_id": "file_3cf0737aefa34b89b7b4443c9467d60c",
          "name": "lecture.mp4"
        }
      ],
      "outputs": []
    }
  ]
}

作业会立即启动,并在后台运行。所需积分此时即被预留,最终只按实际用量扣除。

4. 等待作业结束

每 5 秒查询一次作业,直到其状态不再是 waiting 或 processing。在您自己的应用中,可以通过 Webhook 在作业结束时接收通知,无需反复查询。

# 每隔几秒查询一次,直到状态不再是 waiting 或 processing。
curl https://api.filesokay.com/v1/jobs/job_a1c9531eeb00434aba0058796f1ca517 \
  -H "Authorization: Bearer $FILESOKAY_KEY"
let current = job;
while (current.status === "waiting" || current.status === "processing") {
  await new Promise((resolve) => setTimeout(resolve, 5000));
  current = await api("GET", `/jobs/${job.id}`);
}
console.log(current.status);
current = job
while current["status"] in ("waiting", "processing"):
    time.sleep(5)
    current = api("GET", f"/jobs/{job['id']}")
print(current["status"])
响应
{
  "id": "job_a1c9531eeb00434aba0058796f1ca517",
  "operation": "video.compress",
  "status": "completed",
  "client_reference": null,
  "settings": {
    "audio": "keep",
    "codec": "same",
    "level": "balanced",
    "method": "quality",
    "frame_rate": "original",
    "resolution": "original",
    "output_format": "same"
  },
  "created_at": "2026-12-03T09:00:12Z",
  "started_at": "2026-12-03T09:00:30Z",
  "finished_at": "2026-12-03T09:00:51Z",
  "reserved_credits": 2,
  "charged_credits": 1,
  "tasks": [
    {
      "id": "task_4256d03a73a741afa1821546a2bcba98",
      "status": "completed",
      "progress": 100,
      "reserved_credits": 2,
      "charged_credits": 1,
      "inputs": [
        {
          "file_id": "file_3cf0737aefa34b89b7b4443c9467d60c",
          "name": "lecture.mp4"
        }
      ],
      "outputs": [
        {
          "file_id": "file_8dd09e1ec2fb42c1940e4ef92a153a4e",
          "name": "lecture-compressed.mp4",
          "size": 7268734,
          "download_url": "https://…",
          "download_expires_at": "2026-12-06T09:00:51Z"
        }
      ]
    }
  ]
}

5. 下载结果

每个已完成的任务都会列出其结果,每个结果附带一个下载链接,下载的文件保留其自身的文件名。链接最长有效 7 天,且无需密钥。

# 链接位于作业的 tasks[0].outputs[0].download_url,无需密钥。
curl -o lecture-compressed.mp4 "$DOWNLOAD_URL"
for (const task of current.tasks) {
  for (const output of task.outputs) {
    const res = await fetch(output.download_url);
    if (!res.ok) throw new Error(`${output.name}: ${res.status}`);
    await pipeline(Readable.fromWeb(res.body), fs.createWriteStream(output.name));
    console.log(`Saved ${output.name}: ${output.size} bytes`);
  }
}
for task in current["tasks"]:
    for output in task["outputs"]:
        with requests.get(output["download_url"], stream=True) as res:
            res.raise_for_status()
            with open(output["name"], "wb") as f:
                for chunk in res.iter_content(chunk_size=1 << 20):
                    f.write(chunk)
        print(f"Saved {output['name']}: {output['size']} bytes")

在本示例中,lecture.mp4 从 12.4 MB 压缩到 7.3 MB,消耗 1 积分。

后续步骤

  • 运行作业

    设置、费用预估、批量处理和状态。

  • Webhook

    无需反复查询:作业结束时即可收到签名消息。

  • 错误码

    根据错误码处理每一种错误。