Skip to content

签名上传令牌

签名上传令牌是为客户端上传设计的限时凭证。它们允许浏览器和移动应用直接上传文件到 IPFS Ninja,而无需暴露您的 API 密钥。

典型流程:您的服务器使用 API 密钥生成签名令牌,将其传递给客户端,客户端使用它上传文件。令牌在指定时间后自动过期。

Upload Tokens page for generating time-limited upload tokens

生成签名令牌

POST /upload/signed-url

创建新的签名上传令牌。

参数类型必填描述
namestring令牌标签(如 "Mobile app uploads")。
expiresInnumber令牌有效期(秒)。

请求示例

bash
curl -X POST https://api.ipfs.ninja/upload/signed-url \
  -H "X-Api-Key: bws_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{"name": "Mobile app", "expiresIn": 3600}'

响应 201 Created

json
{
  "token": "sup_a1b2c3d4e5f6789012345678abcdef01...",
  "tokenId": "tok_9876543210abcdef",
  "tokenPrefix": "sup_a1b2c3d4",
  "tokenName": "Mobile app",
  "expiresAt": 1711040400000
}

WARNING

完整令牌仅在创建时返回一次。请妥善保管或直接传递给客户端。

列出签名令牌

GET /signed-tokens

返回账户的所有签名令牌,包括使用统计信息。

请求示例

bash
curl https://api.ipfs.ninja/signed-tokens \
  -H "X-Api-Key: bws_your_api_key_here"

响应 200 OK

json
[
  {
    "tokenId": "tok_9876543210abcdef",
    "tokenPrefix": "sup_a1b2c3d4",
    "tokenName": "Mobile app",
    "expiresAt": 1711040400000,
    "useCount": 15,
    "lastUsedAt": 1711038600000,
    "createdAt": 1711036800000
  }
]

撤销签名令牌

DELETE /signed-tokens/:tokenId

立即撤销签名令牌。此后使用该令牌的任何上传尝试都将被拒绝。

参数类型必填描述
tokenIdstring要撤销的令牌 ID(如 "tok_9876543210abcdef")。

请求示例

bash
curl -X DELETE https://api.ipfs.ninja/signed-tokens/tok_9876543210abcdef \
  -H "X-Api-Key: bws_your_api_key_here"

响应 200 OK

json
{
  "message": "Token revoked"
}

使用签名令牌

要使用签名令牌上传,通过 Authorization 头以 Signed 方案传递:

bash
curl -X POST https://api.ipfs.ninja/upload/new \
  -H "Authorization: Signed sup_a1b2c3d4e5f6789012345678abcdef01..." \
  -H "Content-Type: application/json" \
  -d '{"content": {"name": "example"}, "description": "Client upload"}'

请求正文和响应格式与标准文件上传相同。

使用追踪

每次使用签名令牌时,useCount 递增,lastUsedAt 更新。您可以通过 GET /signed-tokens 监控令牌活动。

签名令牌的前缀记录在分析的 API_KEY_PREFIX 字段中。这意味着您可以像按 API 密钥前缀筛选一样按签名令牌前缀筛选分析数据。详情请参阅分析

示例:浏览器上传

在服务器上生成令牌并在客户端 JavaScript 中使用:

javascript
// Server-side: generate a token valid for 1 hour
const res = await fetch("https://api.ipfs.ninja/upload/signed-url", {
  method: "POST",
  headers: {
    "X-Api-Key": "bws_your_server_key",
    "Content-Type": "application/json"
  },
  body: JSON.stringify({ name: "Web form", expiresIn: 3600 })
});
const { token } = await res.json();
// Pass `token` to the client

// Client-side: upload a file using the signed token
const file = document.getElementById("fileInput").files[0];
const reader = new FileReader();
reader.onload = async () => {
  const base64 = reader.result.split(",")[1];
  const uploadRes = await fetch("https://api.ipfs.ninja/upload/new", {
    method: "POST",
    headers: {
      "Authorization": `Signed ${token}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      content: base64,
      description: "User upload"
    })
  });
  const data = await uploadRes.json();
  console.log("Uploaded:", data.cid);
};
reader.readAsDataURL(file);