查询上传限制
“查询上传限制”章节发送文件前先查询允许的格式、大小、尺寸和时长。能够上传不代表所有工具都可以处理该素材,每个工具还有自己的限制。
/api/v1/assets/upload-limits调用示例
curl --include --fail-with-body --silent --show-error --max-time 60 \ --request GET 'https://www.chaozapi.com/api/v1/assets/upload-limits' \ --header "Authorization: Bearer $GLACIER_API_KEY"// Node.js 22+; save as example.mjs, then: node example.mjsconst key = process.env.GLACIER_API_KEY;if (!key) throw new Error('Set GLACIER_API_KEY');const response = await fetch('https://www.chaozapi.com/api/v1/assets/upload-limits', { method: 'GET', headers: { Authorization: `Bearer ${key}`, }, signal: AbortSignal.timeout(60_000),});const text = await response.text();if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);console.log(response.status, text);# Python 3.10+; standard library; python example.pyimport osimport urllib.requestimport urllib.error
headers = {"Authorization": "Bearer " + os.environ["GLACIER_API_KEY"]}request = urllib.request.Request( "https://www.chaozapi.com/api/v1/assets/upload-limits", method="GET", headers=headers,)try: with urllib.request.urlopen(request, timeout=60) as response: print(response.status, response.read().decode("utf-8"))except urllib.error.HTTPError as error: raise RuntimeError(f"HTTP {error.code}: {error.read().decode('utf-8')}") from error// Go 1.22+; go run example.gopackage main
import ( "fmt" "io" "net/http" "os" "time")
func main() { key := os.Getenv("GLACIER_API_KEY") if key == "" { panic("Set GLACIER_API_KEY") } req, err := http.NewRequest("GET", "https://www.chaozapi.com/api/v1/assets/upload-limits", nil) if err != nil { panic(err) } req.Header.Set("Authorization", "Bearer " + key) client := &http.Client{Timeout: 60 * time.Second} res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() data, err := io.ReadAll(res.Body) if err != nil { panic(err) } if res.StatusCode >= 300 { panic(fmt.Sprintf("HTTP %d: %s", res.StatusCode, data)) } fmt.Println(res.StatusCode, string(data))}// cargo add reqwest@0.13 --features blocking// Save in src/main.rs, then: cargo runuse std::{env, error::Error, time::Duration};
fn main() -> Result<(), Box<dyn Error>> { let client = reqwest::blocking::Client::builder() .timeout(Duration::from_secs(60)).build()?; let response = client.request(reqwest::Method::GET, "https://www.chaozapi.com/api/v1/assets/upload-limits") .bearer_auth(env::var("GLACIER_API_KEY")?) .send()?; let status = response.status(); let text = response.text()?; if !status.is_success() { return Err(format!("HTTP {status}: {text}").into()); } println!("{status} {text}"); Ok(())}// Java 17+; save as Example.java, then: java Example.javaimport java.net.URI;import java.net.http.*;import java.time.Duration;import java.util.Objects;
class Example { public static void main(String[] args) throws Exception { var key = Objects.requireNonNull(System.getenv("GLACIER_API_KEY")); var client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build(); var request = HttpRequest.newBuilder(URI.create("https://www.chaozapi.com/api/v1/assets/upload-limits")) .timeout(Duration.ofSeconds(60)) .header("Authorization", "Bearer " + key) .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() >= 300) throw new IllegalStateException("HTTP " + response.statusCode() + ": " + response.body()); System.out.println(response.statusCode() + " " + response.body()); }}// .NET 8+; dotnet new console; replace Program.cs; dotnet runusing System;using System.Net.Http;using System.Net.Http.Headers;using System.Text;
var key = Environment.GetEnvironmentVariable("GLACIER_API_KEY") ?? throw new InvalidOperationException("Set GLACIER_API_KEY");using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://www.chaozapi.com/api/v1/assets/upload-limits");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);using var response = await client.SendAsync(request);var text = await response.Content.ReadAsStringAsync();if (!response.IsSuccessStatusCode) throw new HttpRequestException($"HTTP {(int)response.StatusCode}: {text}");Console.WriteLine($"{(int)response.StatusCode} {text}");响应字段 · 200
imageobject必填展开字段 / 类型
maxAspectinteger · int64必填长边 / 短边上限
maxBytesinteger · int64必填文件大小上限(字节)
maxDurationMsinteger · int64必填视频时长上限(毫秒)
maxFrameRateinteger · int64必填视频帧率上限(帧/秒)
maxFramesinteger · int64必填视频帧数上限
maxPixelsinteger · int64必填总像素(宽 × 高)上限
maxSideinteger · int64必填长边上限(像素)
minSideinteger · int64必填短边下限(像素)
videoobject必填展开字段 / 类型
maxAspectinteger · int64必填长边 / 短边上限
maxBytesinteger · int64必填文件大小上限(字节)
maxDurationMsinteger · int64必填视频时长上限(毫秒)
maxFrameRateinteger · int64必填视频帧率上限(帧/秒)
maxFramesinteger · int64必填视频帧数上限
maxPixelsinteger · int64必填总像素(宽 × 高)上限
maxSideinteger · int64必填长边上限(像素)
minSideinteger · int64必填短边下限(像素)
申请上传凭证
“申请上传凭证”章节传入文件名、MIME 类型与准确字节数。请把示例中的 123456 改为实际文件大小。201 响应包含 assetId、uploadUrl、method、headers(名称 / 值二元数组)、fileField 和 expiresAt。将响应保存为本地 ticket.json 供下一步读取;其中包含临时签名地址,请妥善保管。
/api/v1/assets/uploads路径、查询与请求头
| 参数 | 位置 | 类型与约束 |
|---|---|---|
Idempotency-Key可选 | header | string建议提供;账户内同键同参数恢复同一素材,冲突409,已删除410;与任务幂等键分开计数 maxLength: 128 · pattern: "^[A-Za-z0-9._:-]+$" |
请求体字段 · application/json
estDurationMsinteger · int64可选前端预探测时长毫秒(可选)
minimum: 0
estHeightinteger · int64可选前端预探测高度(可选)
minimum: 1 · maximum: 65536
estWidthinteger · int64可选前端预探测宽度(可选)
minimum: 1 · maximum: 65536
mimeTypestring必填multipartboolean可选用表单(multipart/form-data)POST 上传:给只能发表单的客户端(微信小程序 wx.uploadFile);默认 PUT 原始字节
namestring必填resumableboolean可选启用分片与断点续传;调用 resumeUpload 查询进度、createUploadPart 签发分片凭证,最后 completeUpload 合并入库
routingMode"auto" | "cloud"可选auto 按节点容量自动选路;cloud 强制对象存储。开放 API 省略时按 cloud 处理
serviceHintstring可选可选:后续计划使用的工具 ID(用于节点亲和选路)
maxLength: 64
sizeBytesinteger · int64必填
调用示例
# Set GLACIER_IDEMPOTENCY_KEY once per logical task; reuse it AND the body on retries.curl --include --fail-with-body --silent --show-error --max-time 60 \ --request POST 'https://www.chaozapi.com/api/v1/assets/uploads' \ --header "Authorization: Bearer $GLACIER_API_KEY" \ --header "Idempotency-Key: $GLACIER_IDEMPOTENCY_KEY" \ --header 'Content-Type: application/json' \ --data-raw '{ "name": "input.png", "mimeType": "image/png", "sizeBytes": 123456}'// Node.js 22+; save as example.mjs, then: node example.mjsconst key = process.env.GLACIER_API_KEY;if (!key) throw new Error('Set GLACIER_API_KEY');const idempotencyKey = process.env.GLACIER_IDEMPOTENCY_KEY;if (!idempotencyKey) throw new Error('Set a stable GLACIER_IDEMPOTENCY_KEY');const response = await fetch('https://www.chaozapi.com/api/v1/assets/uploads', { method: 'POST', headers: { Authorization: `Bearer ${key}`, 'Idempotency-Key': idempotencyKey, 'Content-Type': 'application/json', }, body: JSON.stringify({ "name": "input.png", "mimeType": "image/png", "sizeBytes": 123456}), signal: AbortSignal.timeout(60_000),});const text = await response.text();if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);console.log(response.status, text);# Python 3.10+; standard library; python example.pyimport osimport urllib.requestimport urllib.error
headers = {"Authorization": "Bearer " + os.environ["GLACIER_API_KEY"]}headers["Idempotency-Key"] = os.environ["GLACIER_IDEMPOTENCY_KEY"]headers["Content-Type"] = "application/json"request = urllib.request.Request( "https://www.chaozapi.com/api/v1/assets/uploads", method="POST", headers=headers, data="""{ "name": "input.png", "mimeType": "image/png", "sizeBytes": 123456}""".encode("utf-8"),)try: with urllib.request.urlopen(request, timeout=60) as response: print(response.status, response.read().decode("utf-8"))except urllib.error.HTTPError as error: raise RuntimeError(f"HTTP {error.code}: {error.read().decode('utf-8')}") from error// Go 1.22+; go run example.gopackage main
import ( "fmt" "io" "net/http" "os" "strings" "time")
func main() { key := os.Getenv("GLACIER_API_KEY") if key == "" { panic("Set GLACIER_API_KEY") } idem := os.Getenv("GLACIER_IDEMPOTENCY_KEY") if idem == "" { panic("Set a stable GLACIER_IDEMPOTENCY_KEY") } req, err := http.NewRequest("POST", "https://www.chaozapi.com/api/v1/assets/uploads", strings.NewReader(`{ "name": "input.png", "mimeType": "image/png", "sizeBytes": 123456}`)) if err != nil { panic(err) } req.Header.Set("Authorization", "Bearer " + key) req.Header.Set("Idempotency-Key", idem) req.Header.Set("Content-Type", "application/json") client := &http.Client{Timeout: 60 * time.Second} res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() data, err := io.ReadAll(res.Body) if err != nil { panic(err) } if res.StatusCode >= 300 { panic(fmt.Sprintf("HTTP %d: %s", res.StatusCode, data)) } fmt.Println(res.StatusCode, string(data))}// cargo add reqwest@0.13 --features blocking// Save in src/main.rs, then: cargo runuse std::{env, error::Error, time::Duration};
fn main() -> Result<(), Box<dyn Error>> { let client = reqwest::blocking::Client::builder() .timeout(Duration::from_secs(60)).build()?; let response = client.request(reqwest::Method::POST, "https://www.chaozapi.com/api/v1/assets/uploads") .bearer_auth(env::var("GLACIER_API_KEY")?) .header("Idempotency-Key", env::var("GLACIER_IDEMPOTENCY_KEY")?) .header("Content-Type", "application/json") .body(r#"{ "name": "input.png", "mimeType": "image/png", "sizeBytes": 123456}"#) .send()?; let status = response.status(); let text = response.text()?; if !status.is_success() { return Err(format!("HTTP {status}: {text}").into()); } println!("{status} {text}"); Ok(())}// Java 17+; save as Example.java, then: java Example.javaimport java.net.URI;import java.net.http.*;import java.time.Duration;import java.util.Objects;
class Example { public static void main(String[] args) throws Exception { var key = Objects.requireNonNull(System.getenv("GLACIER_API_KEY")); var client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build(); var request = HttpRequest.newBuilder(URI.create("https://www.chaozapi.com/api/v1/assets/uploads")) .timeout(Duration.ofSeconds(60)) .header("Authorization", "Bearer " + key) .header("Idempotency-Key", Objects.requireNonNull(System.getenv("GLACIER_IDEMPOTENCY_KEY"))) .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("""{ "name": "input.png", "mimeType": "image/png", "sizeBytes": 123456}""")) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() >= 300) throw new IllegalStateException("HTTP " + response.statusCode() + ": " + response.body()); System.out.println(response.statusCode() + " " + response.body()); }}// .NET 8+; dotnet new console; replace Program.cs; dotnet runusing System;using System.Net.Http;using System.Net.Http.Headers;using System.Text;
var key = Environment.GetEnvironmentVariable("GLACIER_API_KEY") ?? throw new InvalidOperationException("Set GLACIER_API_KEY");using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://www.chaozapi.com/api/v1/assets/uploads");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);request.Headers.Add("Idempotency-Key", Environment.GetEnvironmentVariable("GLACIER_IDEMPOTENCY_KEY") ?? throw new InvalidOperationException("Set a stable GLACIER_IDEMPOTENCY_KEY"));request.Content = new StringContent("""{ "name": "input.png", "mimeType": "image/png", "sizeBytes": 123456}""", Encoding.UTF8, "application/json");using var response = await client.SendAsync(request);var text = await response.Content.ReadAsStringAsync();if (!response.IsSuccessStatusCode) throw new HttpRequestException($"HTTP {(int)response.StatusCode}: {text}");Console.WriteLine($"{(int)response.StatusCode} {text}");响应字段 · 201
assetIdstring必填chunkSizeinteger · int64必填分片大小(字节);0 表示整文件直传
cosobject可选腾讯云 COS STS 临时密钥(仅 Web SPA 直传 COS 时返回)
展开字段 / 类型
bucketstring必填COS 存储桶名称(含 APPID,如 bucket-1250000000)
expiredTimeinteger · int64必填临时密钥过期时间戳(秒)
keystring必填包含存储前缀的完整对象路径
regionstring必填COS 地域(如 ap-guangzhou)
sessionTokenstring必填STS 临时安全令牌 XCosSecurityToken
startTimeinteger · int64必填临时密钥生效时间戳(秒)
tmpSecretIdstring必填STS 临时 SecretId
tmpSecretKeystring必填STS 临时 SecretKey
estimatedQueueSecondsinteger · int64可选目标节点预估排队秒数
expiresAtstring · date-time必填fileFieldstring | null必填method 为 POST(表单上传)时文件所在的字段名;PUT 为 null
formFieldsstring[][]可选表单 POST 直传对象存储时附带的签名字段
展开字段 / 类型
stringheadersstring[][]必填展开字段 / 类型
stringmethod"PUT" | "POST"必填nodeIdstring可选直传节点 ID
routestring可选上传路径:node_direct 或 object_store
routeGenerationinteger · int64可选上传会话代次
status"pending" | "preparing" | "ready" | "failed"可选pending可上传;幂等恢复返回preparing/ready时uploadUrl为空,不应重传
uploadUrlstring必填
建议携带 Idempotency-Key,并在发送前保存键和请求体。相同账户、相同键和参数可找回同一个 assetId;同键不同参数返回 409 IDEMPOTENCY_CONFLICT。上传键与任务键分别计数。为兼容旧调用,上传键仍可省略,但省略后重新申请会新建素材。
开放 API 默认向 COS 直传。省略 routingMode 或显式传 "cloud" 时,COS 不可用返回 503 UPLOAD_STORAGE_UNAVAILABLE。新客户端可传 "routingMode":"auto",由控制面根据容量选择 GPU 节点直传或 COS。文件始终按返回的 uploadUrl 和方法发送。
直传文件字节
“直传文件字节”章节下面使用默认 PUT 凭证,把 input.png 流式上传到返回的 URL,并使用返回的请求头。这是存储请求,不经过 /api/v1,不要附带 API Key。
# Save the upload-ticket response as ticket.json. Requires jq.# The ticket must be for input.png with its exact byte length.test "$(jq -r '.method' ticket.json)" = PUT || exit 1headers=()while IFS= read -r header; do headers+=(--header "$header"); done < <( jq -r '.headers[] | .[0] + ": " + .[1]' ticket.json)curl --fail-with-body --silent --show-error --max-time 1800 \ --request PUT "$(jq -r '.uploadUrl' ticket.json)" \ "${headers[@]}" --upload-file input.png// Node.js 22+; example.mjsimport { readFile, stat } from 'node:fs/promises';import { createReadStream } from 'node:fs';const ticket = JSON.parse(await readFile('ticket.json', 'utf8'));if (ticket.method !== 'PUT') throw new Error('Request a default PUT ticket');const headers = Object.fromEntries(ticket.headers);headers['Content-Length'] = String((await stat('input.png')).size);const response = await fetch(ticket.uploadUrl, { method: 'PUT', headers, body: createReadStream('input.png'), duplex: 'half', signal: AbortSignal.timeout(1_800_000),});if (!response.ok) throw new Error(await response.text());console.log('Uploaded; now confirm asset', ticket.assetId);# Python 3.10+; standard libraryimport jsonimport osimport urllib.requestwith open('ticket.json', encoding='utf-8') as source: ticket = json.load(source)if ticket['method'] != 'PUT': raise ValueError('Request a default PUT ticket')headers = dict(ticket['headers'])headers['Content-Length'] = str(os.path.getsize('input.png'))with open('input.png', 'rb') as source: request = urllib.request.Request(ticket['uploadUrl'], data=source, headers=headers, method='PUT') with urllib.request.urlopen(request, timeout=1800) as response: print(response.status, 'Confirm asset', ticket['assetId'])// go run upload.gopackage mainimport ( "encoding/json" "fmt" "net/http" "os" "time")func main() { var ticket struct { AssetID string UploadURL string Method string Headers [][2]string } raw, err := os.ReadFile("ticket.json") if err != nil { panic(err) } if err = json.Unmarshal(raw, &ticket); err != nil { panic(err) } if ticket.Method != "PUT" { panic("Request a default PUT ticket") } file, err := os.Open("input.png") if err != nil { panic(err) } defer file.Close() info, err := file.Stat() if err != nil { panic(err) } req, err := http.NewRequest("PUT", ticket.UploadURL, file) if err != nil { panic(err) } req.ContentLength = info.Size() for _, h := range ticket.Headers { req.Header.Set(h[0], h[1]) } res, err := (&http.Client{Timeout: 30 * time.Minute}).Do(req) if err != nil { panic(err) } defer res.Body.Close() if res.StatusCode >= 300 { panic(res.Status) } fmt.Println("Uploaded; confirm asset", ticket.AssetID)}// cargo add reqwest@0.13 --features blocking// cargo add serde_jsonuse std::{error::Error, fs::File, time::Duration};fn main() -> Result<(), Box<dyn Error>> { let ticket: serde_json::Value = serde_json::from_reader(File::open("ticket.json")?)?; if ticket["method"] != "PUT" { return Err("Request a default PUT ticket".into()); } let file = File::open("input.png")?; let client = reqwest::blocking::Client::builder() .timeout(Duration::from_secs(1800)).build()?; let mut request = client.put(ticket["uploadUrl"].as_str().ok_or("Missing uploadUrl")?) .header("Content-Length", file.metadata()?.len()); for header in ticket["headers"].as_array().ok_or("Missing headers")? { request = request.header(header[0].as_str().ok_or("Invalid header")?, header[1].as_str().ok_or("Invalid header")?); } request.body(reqwest::blocking::Body::new(file)).send()?.error_for_status()?; println!("Uploaded; confirm asset {}", ticket["assetId"]); Ok(())}// Java 17+; add com.fasterxml.jackson.core:jackson-databind to your project.import com.fasterxml.jackson.databind.ObjectMapper;import java.nio.file.Path;import java.net.URI;import java.net.http.*;import java.time.Duration;class Upload { public static void main(String[] args) throws Exception { var ticket = new ObjectMapper().readTree(Path.of("ticket.json").toFile()); if (!ticket.get("method").asText().equals("PUT")) throw new IllegalArgumentException("Request a default PUT ticket"); var request = HttpRequest.newBuilder(URI.create(ticket.get("uploadUrl").asText())) .timeout(Duration.ofMinutes(30)); for (var header : ticket.get("headers")) request.header(header.get(0).asText(), header.get(1).asText()); var response = HttpClient.newHttpClient().send(request .PUT(HttpRequest.BodyPublishers.ofFile(Path.of("input.png"))).build(), HttpResponse.BodyHandlers.ofString()); if (response.statusCode() >= 300) throw new IllegalStateException(response.body()); System.out.println("Uploaded; confirm asset " + ticket.get("assetId").asText()); }}// .NET 8+; Program.csusing System;using System.IO;using System.Net.Http;using System.Text.Json;using var ticket = JsonDocument.Parse(await File.ReadAllTextAsync("ticket.json"));var root = ticket.RootElement;if (root.GetProperty("method").GetString() != "PUT") throw new InvalidOperationException("Request a default PUT ticket");using var client = new HttpClient { Timeout = TimeSpan.FromMinutes(30) };using var file = File.OpenRead("input.png");using var request = new HttpRequestMessage(HttpMethod.Put, root.GetProperty("uploadUrl").GetString());request.Content = new StreamContent(file);foreach (var header in root.GetProperty("headers").EnumerateArray()) { var name = header[0].GetString()!; var value = header[1].GetString(); if (!request.Headers.TryAddWithoutValidation(name, value)) request.Content.Headers.TryAddWithoutValidation(name, value);}using var response = await client.SendAsync(request);response.EnsureSuccessStatusCode();Console.WriteLine("Uploaded; confirm asset " + root.GetProperty("assetId").GetString());如果申请凭证时明确传入 multipart: true,返回的方法会变成 POST。使用 multipart/form-data,先添加全部 formFields,最后添加 fileField 文件字段,保留返回的请求头,并让 HTTP 库自动设置 multipart boundary。multipart 指表单上传;大文件分片使用 resumable: true。
凭据失效而会话仍有效时,使用下列接口重新签发,无需新建素材。若响应 status 为 preparing 或 ready,uploadUrl 为空,不要再上传,继续查询状态。会话过期返回 410 UPLOAD_SESSION_EXPIRED。
/api/v1/assets/{assetId}/upload-ticket路径、查询与请求头
| 参数 | 位置 | 类型与约束 |
|---|---|---|
assetId必填 | path | string素材 ID |
请求体字段 · application/json
multipartboolean可选使用表单POST;默认PUT;不创建新的素材或分片会话
调用示例
curl --include --fail-with-body --silent --show-error --max-time 60 \ --request POST 'https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-ticket' \ --header "Authorization: Bearer $GLACIER_API_KEY"// Node.js 22+; save as example.mjs, then: node example.mjsconst key = process.env.GLACIER_API_KEY;if (!key) throw new Error('Set GLACIER_API_KEY');const response = await fetch('https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-ticket', { method: 'POST', headers: { Authorization: `Bearer ${key}`, }, signal: AbortSignal.timeout(60_000),});const text = await response.text();if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);console.log(response.status, text);# Python 3.10+; standard library; python example.pyimport osimport urllib.requestimport urllib.error
headers = {"Authorization": "Bearer " + os.environ["GLACIER_API_KEY"]}request = urllib.request.Request( "https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-ticket", method="POST", headers=headers,)try: with urllib.request.urlopen(request, timeout=60) as response: print(response.status, response.read().decode("utf-8"))except urllib.error.HTTPError as error: raise RuntimeError(f"HTTP {error.code}: {error.read().decode('utf-8')}") from error// Go 1.22+; go run example.gopackage main
import ( "fmt" "io" "net/http" "os" "time")
func main() { key := os.Getenv("GLACIER_API_KEY") if key == "" { panic("Set GLACIER_API_KEY") } req, err := http.NewRequest("POST", "https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-ticket", nil) if err != nil { panic(err) } req.Header.Set("Authorization", "Bearer " + key) client := &http.Client{Timeout: 60 * time.Second} res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() data, err := io.ReadAll(res.Body) if err != nil { panic(err) } if res.StatusCode >= 300 { panic(fmt.Sprintf("HTTP %d: %s", res.StatusCode, data)) } fmt.Println(res.StatusCode, string(data))}// cargo add reqwest@0.13 --features blocking// Save in src/main.rs, then: cargo runuse std::{env, error::Error, time::Duration};
fn main() -> Result<(), Box<dyn Error>> { let client = reqwest::blocking::Client::builder() .timeout(Duration::from_secs(60)).build()?; let response = client.request(reqwest::Method::POST, "https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-ticket") .bearer_auth(env::var("GLACIER_API_KEY")?) .send()?; let status = response.status(); let text = response.text()?; if !status.is_success() { return Err(format!("HTTP {status}: {text}").into()); } println!("{status} {text}"); Ok(())}// Java 17+; save as Example.java, then: java Example.javaimport java.net.URI;import java.net.http.*;import java.time.Duration;import java.util.Objects;
class Example { public static void main(String[] args) throws Exception { var key = Objects.requireNonNull(System.getenv("GLACIER_API_KEY")); var client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build(); var request = HttpRequest.newBuilder(URI.create("https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-ticket")) .timeout(Duration.ofSeconds(60)) .header("Authorization", "Bearer " + key) .method("POST", HttpRequest.BodyPublishers.noBody()) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() >= 300) throw new IllegalStateException("HTTP " + response.statusCode() + ": " + response.body()); System.out.println(response.statusCode() + " " + response.body()); }}// .NET 8+; dotnet new console; replace Program.cs; dotnet runusing System;using System.Net.Http;using System.Net.Http.Headers;using System.Text;
var key = Environment.GetEnvironmentVariable("GLACIER_API_KEY") ?? throw new InvalidOperationException("Set GLACIER_API_KEY");using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-ticket");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);using var response = await client.SendAsync(request);var text = await response.Content.ReadAsStringAsync();if (!response.IsSuccessStatusCode) throw new HttpRequestException($"HTTP {(int)response.StatusCode}: {text}");Console.WriteLine($"{(int)response.StatusCode} {text}");响应字段 · 200
assetIdstring必填chunkSizeinteger · int64必填分片大小(字节);0 表示整文件直传
cosobject可选腾讯云 COS STS 临时密钥(仅 Web SPA 直传 COS 时返回)
展开字段 / 类型
bucketstring必填COS 存储桶名称(含 APPID,如 bucket-1250000000)
expiredTimeinteger · int64必填临时密钥过期时间戳(秒)
keystring必填包含存储前缀的完整对象路径
regionstring必填COS 地域(如 ap-guangzhou)
sessionTokenstring必填STS 临时安全令牌 XCosSecurityToken
startTimeinteger · int64必填临时密钥生效时间戳(秒)
tmpSecretIdstring必填STS 临时 SecretId
tmpSecretKeystring必填STS 临时 SecretKey
estimatedQueueSecondsinteger · int64可选目标节点预估排队秒数
expiresAtstring · date-time必填fileFieldstring | null必填method 为 POST(表单上传)时文件所在的字段名;PUT 为 null
formFieldsstring[][]可选表单 POST 直传对象存储时附带的签名字段
展开字段 / 类型
stringheadersstring[][]必填展开字段 / 类型
stringmethod"PUT" | "POST"必填nodeIdstring可选直传节点 ID
routestring可选上传路径:node_direct 或 object_store
routeGenerationinteger · int64可选上传会话代次
status"pending" | "preparing" | "ready" | "failed"可选pending可上传;幂等恢复返回preparing/ready时uploadUrl为空,不应重传
uploadUrlstring必填
若 route 为 node_direct 且传输失败,可申请换到对象存储并重新上传。换线沿用 assetId,使用新凭证和新 routeGeneration。两个线路的分片分别保存,客户端应从新线路重新上传。直接从 COS 开始的会话未配置备用通道时返回 409。
/api/v1/assets/{assetId}/upload-fallback路径、查询与请求头
| 参数 | 位置 | 类型与约束 |
|---|---|---|
assetId必填 | path | string素材 ID |
请求体字段 · application/json
multipartboolean可选reasonstring可选触发换路原因(如 slow_speed、timeout、network_error)
maxLength: 120
resumableboolean可选
调用示例
curl --include --fail-with-body --silent --show-error --max-time 60 \ --request POST 'https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-fallback' \ --header "Authorization: Bearer $GLACIER_API_KEY" \ --header 'Content-Type: application/json' \ --data-raw '{ "reason": "network_timeout"}'// Node.js 22+; save as example.mjs, then: node example.mjsconst key = process.env.GLACIER_API_KEY;if (!key) throw new Error('Set GLACIER_API_KEY');const response = await fetch('https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-fallback', { method: 'POST', headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "reason": "network_timeout"}), signal: AbortSignal.timeout(60_000),});const text = await response.text();if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);console.log(response.status, text);# Python 3.10+; standard library; python example.pyimport osimport urllib.requestimport urllib.error
headers = {"Authorization": "Bearer " + os.environ["GLACIER_API_KEY"]}headers["Content-Type"] = "application/json"request = urllib.request.Request( "https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-fallback", method="POST", headers=headers, data="""{ "reason": "network_timeout"}""".encode("utf-8"),)try: with urllib.request.urlopen(request, timeout=60) as response: print(response.status, response.read().decode("utf-8"))except urllib.error.HTTPError as error: raise RuntimeError(f"HTTP {error.code}: {error.read().decode('utf-8')}") from error// Go 1.22+; go run example.gopackage main
import ( "fmt" "io" "net/http" "os" "strings" "time")
func main() { key := os.Getenv("GLACIER_API_KEY") if key == "" { panic("Set GLACIER_API_KEY") } req, err := http.NewRequest("POST", "https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-fallback", strings.NewReader(`{ "reason": "network_timeout"}`)) if err != nil { panic(err) } req.Header.Set("Authorization", "Bearer " + key) req.Header.Set("Content-Type", "application/json") client := &http.Client{Timeout: 60 * time.Second} res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() data, err := io.ReadAll(res.Body) if err != nil { panic(err) } if res.StatusCode >= 300 { panic(fmt.Sprintf("HTTP %d: %s", res.StatusCode, data)) } fmt.Println(res.StatusCode, string(data))}// cargo add reqwest@0.13 --features blocking// Save in src/main.rs, then: cargo runuse std::{env, error::Error, time::Duration};
fn main() -> Result<(), Box<dyn Error>> { let client = reqwest::blocking::Client::builder() .timeout(Duration::from_secs(60)).build()?; let response = client.request(reqwest::Method::POST, "https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-fallback") .bearer_auth(env::var("GLACIER_API_KEY")?) .header("Content-Type", "application/json") .body(r#"{ "reason": "network_timeout"}"#) .send()?; let status = response.status(); let text = response.text()?; if !status.is_success() { return Err(format!("HTTP {status}: {text}").into()); } println!("{status} {text}"); Ok(())}// Java 17+; save as Example.java, then: java Example.javaimport java.net.URI;import java.net.http.*;import java.time.Duration;import java.util.Objects;
class Example { public static void main(String[] args) throws Exception { var key = Objects.requireNonNull(System.getenv("GLACIER_API_KEY")); var client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build(); var request = HttpRequest.newBuilder(URI.create("https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-fallback")) .timeout(Duration.ofSeconds(60)) .header("Authorization", "Bearer " + key) .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("""{ "reason": "network_timeout"}""")) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() >= 300) throw new IllegalStateException("HTTP " + response.statusCode() + ": " + response.body()); System.out.println(response.statusCode() + " " + response.body()); }}// .NET 8+; dotnet new console; replace Program.cs; dotnet runusing System;using System.Net.Http;using System.Net.Http.Headers;using System.Text;
var key = Environment.GetEnvironmentVariable("GLACIER_API_KEY") ?? throw new InvalidOperationException("Set GLACIER_API_KEY");using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-fallback");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);request.Content = new StringContent("""{ "reason": "network_timeout"}""", Encoding.UTF8, "application/json");using var response = await client.SendAsync(request);var text = await response.Content.ReadAsStringAsync();if (!response.IsSuccessStatusCode) throw new HttpRequestException($"HTTP {(int)response.StatusCode}: {text}");Console.WriteLine($"{(int)response.StatusCode} {text}");响应字段 · 200
assetIdstring必填chunkSizeinteger · int64必填分片大小(字节);0 表示整文件直传
cosobject可选腾讯云 COS STS 临时密钥(仅 Web SPA 直传 COS 时返回)
展开字段 / 类型
bucketstring必填COS 存储桶名称(含 APPID,如 bucket-1250000000)
expiredTimeinteger · int64必填临时密钥过期时间戳(秒)
keystring必填包含存储前缀的完整对象路径
regionstring必填COS 地域(如 ap-guangzhou)
sessionTokenstring必填STS 临时安全令牌 XCosSecurityToken
startTimeinteger · int64必填临时密钥生效时间戳(秒)
tmpSecretIdstring必填STS 临时 SecretId
tmpSecretKeystring必填STS 临时 SecretKey
estimatedQueueSecondsinteger · int64可选目标节点预估排队秒数
expiresAtstring · date-time必填fileFieldstring | null必填method 为 POST(表单上传)时文件所在的字段名;PUT 为 null
formFieldsstring[][]可选表单 POST 直传对象存储时附带的签名字段
展开字段 / 类型
stringheadersstring[][]必填展开字段 / 类型
stringmethod"PUT" | "POST"必填nodeIdstring可选直传节点 ID
routestring可选上传路径:node_direct 或 object_store
routeGenerationinteger · int64可选上传会话代次
status"pending" | "preparing" | "ready" | "failed"可选pending可上传;幂等恢复返回preparing/ready时uploadUrl为空,不应重传
uploadUrlstring必填
确认上传完成
“确认上传完成”章节大文件可按上传凭证中的分片配置续传。先恢复会话,读取 chunkSize、parts、maxConcurrency 和 resumeUntil,跳过已经保存且哈希一致的分片;分片编号从 1 开始。对每个待传分片计算原始字节的 SHA-256,申请该分片的直传凭证,再按凭证的 method、headers 和 fileField 上传。示例哈希必须替换为实际分片的哈希。全部分片上传后,仍使用下方的确认接口入库。
分片大小使用服务端返回的 chunkSize,最后一片可更小。并发不超过 maxConcurrency。申请分片凭证和确认完成时都使用当前 routeGeneration。完成请求例如 {"routeGeneration":1,"parts":[{"number":1,"etag":"实际ETag","sha256":"实际哈希"}]},请替换为实际代次和完整分片记录。服务端会核对存储中的分片数量与总大小。
/api/v1/assets/{assetId}/upload-session路径、查询与请求头
| 参数 | 位置 | 类型与约束 |
|---|---|---|
assetId必填 | path | string素材 ID |
调用示例
curl --include --fail-with-body --silent --show-error --max-time 60 \ --request POST 'https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-session' \ --header "Authorization: Bearer $GLACIER_API_KEY"// Node.js 22+; save as example.mjs, then: node example.mjsconst key = process.env.GLACIER_API_KEY;if (!key) throw new Error('Set GLACIER_API_KEY');const response = await fetch('https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-session', { method: 'POST', headers: { Authorization: `Bearer ${key}`, }, signal: AbortSignal.timeout(60_000),});const text = await response.text();if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);console.log(response.status, text);# Python 3.10+; standard library; python example.pyimport osimport urllib.requestimport urllib.error
headers = {"Authorization": "Bearer " + os.environ["GLACIER_API_KEY"]}request = urllib.request.Request( "https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-session", method="POST", headers=headers,)try: with urllib.request.urlopen(request, timeout=60) as response: print(response.status, response.read().decode("utf-8"))except urllib.error.HTTPError as error: raise RuntimeError(f"HTTP {error.code}: {error.read().decode('utf-8')}") from error// Go 1.22+; go run example.gopackage main
import ( "fmt" "io" "net/http" "os" "time")
func main() { key := os.Getenv("GLACIER_API_KEY") if key == "" { panic("Set GLACIER_API_KEY") } req, err := http.NewRequest("POST", "https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-session", nil) if err != nil { panic(err) } req.Header.Set("Authorization", "Bearer " + key) client := &http.Client{Timeout: 60 * time.Second} res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() data, err := io.ReadAll(res.Body) if err != nil { panic(err) } if res.StatusCode >= 300 { panic(fmt.Sprintf("HTTP %d: %s", res.StatusCode, data)) } fmt.Println(res.StatusCode, string(data))}// cargo add reqwest@0.13 --features blocking// Save in src/main.rs, then: cargo runuse std::{env, error::Error, time::Duration};
fn main() -> Result<(), Box<dyn Error>> { let client = reqwest::blocking::Client::builder() .timeout(Duration::from_secs(60)).build()?; let response = client.request(reqwest::Method::POST, "https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-session") .bearer_auth(env::var("GLACIER_API_KEY")?) .send()?; let status = response.status(); let text = response.text()?; if !status.is_success() { return Err(format!("HTTP {status}: {text}").into()); } println!("{status} {text}"); Ok(())}// Java 17+; save as Example.java, then: java Example.javaimport java.net.URI;import java.net.http.*;import java.time.Duration;import java.util.Objects;
class Example { public static void main(String[] args) throws Exception { var key = Objects.requireNonNull(System.getenv("GLACIER_API_KEY")); var client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build(); var request = HttpRequest.newBuilder(URI.create("https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-session")) .timeout(Duration.ofSeconds(60)) .header("Authorization", "Bearer " + key) .method("POST", HttpRequest.BodyPublishers.noBody()) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() >= 300) throw new IllegalStateException("HTTP " + response.statusCode() + ": " + response.body()); System.out.println(response.statusCode() + " " + response.body()); }}// .NET 8+; dotnet new console; replace Program.cs; dotnet runusing System;using System.Net.Http;using System.Net.Http.Headers;using System.Text;
var key = Environment.GetEnvironmentVariable("GLACIER_API_KEY") ?? throw new InvalidOperationException("Set GLACIER_API_KEY");using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-session");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);using var response = await client.SendAsync(request);var text = await response.Content.ReadAsStringAsync();if (!response.IsSuccessStatusCode) throw new HttpRequestException($"HTTP {(int)response.StatusCode}: {text}");Console.WriteLine($"{(int)response.StatusCode} {text}");响应字段 · 200
assetIdstring必填chunkSizeinteger · int64必填completeboolean必填cosobject可选腾讯云 COS STS 临时密钥(SPA 断点续传刷新凭证时返回)
展开字段 / 类型
bucketstring必填COS 存储桶名称(含 APPID,如 bucket-1250000000)
expiredTimeinteger · int64必填临时密钥过期时间戳(秒)
keystring必填包含存储前缀的完整对象路径
regionstring必填COS 地域(如 ap-guangzhou)
sessionTokenstring必填STS 临时安全令牌 XCosSecurityToken
startTimeinteger · int64必填临时密钥生效时间戳(秒)
tmpSecretIdstring必填STS 临时 SecretId
tmpSecretKeystring必填STS 临时 SecretKey
maxConcurrencyinteger · int64必填partsobject[]必填展开字段 / 类型
etagstring可选numberinteger · int64必填sha256string必填sizeBytesinteger · int64必填
resumeUntilstring · date-time必填继续上传或查询会话会续期;超过有效期后临时文件会被清理
routestring可选routeGenerationinteger · int64可选sizeBytesinteger · int64必填
/api/v1/assets/{assetId}/upload-parts路径、查询与请求头
| 参数 | 位置 | 类型与约束 |
|---|---|---|
assetId必填 | path | string素材 ID |
请求体字段 · application/json
multipartboolean可选小程序使用表单 POST 上传分片
numberinteger · int64必填minimum: 1 · maximum: 1024
routeGenerationinteger · int64可选续传时使用当前上传线路代次
minimum: 1
sha256string必填本分片原始字节的 SHA-256,小写十六进制
pattern: "^[a-f0-9]{64}$"
调用示例
curl --include --fail-with-body --silent --show-error --max-time 60 \ --request POST 'https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-parts' \ --header "Authorization: Bearer $GLACIER_API_KEY" \ --header 'Content-Type: application/json' \ --data-raw '{ "number": 1, "routeGeneration": 1, "sha256": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}'// Node.js 22+; save as example.mjs, then: node example.mjsconst key = process.env.GLACIER_API_KEY;if (!key) throw new Error('Set GLACIER_API_KEY');const response = await fetch('https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-parts', { method: 'POST', headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "number": 1, "routeGeneration": 1, "sha256": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}), signal: AbortSignal.timeout(60_000),});const text = await response.text();if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);console.log(response.status, text);# Python 3.10+; standard library; python example.pyimport osimport urllib.requestimport urllib.error
headers = {"Authorization": "Bearer " + os.environ["GLACIER_API_KEY"]}headers["Content-Type"] = "application/json"request = urllib.request.Request( "https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-parts", method="POST", headers=headers, data="""{ "number": 1, "routeGeneration": 1, "sha256": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}""".encode("utf-8"),)try: with urllib.request.urlopen(request, timeout=60) as response: print(response.status, response.read().decode("utf-8"))except urllib.error.HTTPError as error: raise RuntimeError(f"HTTP {error.code}: {error.read().decode('utf-8')}") from error// Go 1.22+; go run example.gopackage main
import ( "fmt" "io" "net/http" "os" "strings" "time")
func main() { key := os.Getenv("GLACIER_API_KEY") if key == "" { panic("Set GLACIER_API_KEY") } req, err := http.NewRequest("POST", "https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-parts", strings.NewReader(`{ "number": 1, "routeGeneration": 1, "sha256": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}`)) if err != nil { panic(err) } req.Header.Set("Authorization", "Bearer " + key) req.Header.Set("Content-Type", "application/json") client := &http.Client{Timeout: 60 * time.Second} res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() data, err := io.ReadAll(res.Body) if err != nil { panic(err) } if res.StatusCode >= 300 { panic(fmt.Sprintf("HTTP %d: %s", res.StatusCode, data)) } fmt.Println(res.StatusCode, string(data))}// cargo add reqwest@0.13 --features blocking// Save in src/main.rs, then: cargo runuse std::{env, error::Error, time::Duration};
fn main() -> Result<(), Box<dyn Error>> { let client = reqwest::blocking::Client::builder() .timeout(Duration::from_secs(60)).build()?; let response = client.request(reqwest::Method::POST, "https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-parts") .bearer_auth(env::var("GLACIER_API_KEY")?) .header("Content-Type", "application/json") .body(r#"{ "number": 1, "routeGeneration": 1, "sha256": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}"#) .send()?; let status = response.status(); let text = response.text()?; if !status.is_success() { return Err(format!("HTTP {status}: {text}").into()); } println!("{status} {text}"); Ok(())}// Java 17+; save as Example.java, then: java Example.javaimport java.net.URI;import java.net.http.*;import java.time.Duration;import java.util.Objects;
class Example { public static void main(String[] args) throws Exception { var key = Objects.requireNonNull(System.getenv("GLACIER_API_KEY")); var client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build(); var request = HttpRequest.newBuilder(URI.create("https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-parts")) .timeout(Duration.ofSeconds(60)) .header("Authorization", "Bearer " + key) .header("Content-Type", "application/json") .method("POST", HttpRequest.BodyPublishers.ofString("""{ "number": 1, "routeGeneration": 1, "sha256": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}""")) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() >= 300) throw new IllegalStateException("HTTP " + response.statusCode() + ": " + response.body()); System.out.println(response.statusCode() + " " + response.body()); }}// .NET 8+; dotnet new console; replace Program.cs; dotnet runusing System;using System.Net.Http;using System.Net.Http.Headers;using System.Text;
var key = Environment.GetEnvironmentVariable("GLACIER_API_KEY") ?? throw new InvalidOperationException("Set GLACIER_API_KEY");using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-parts");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);request.Content = new StringContent("""{ "number": 1, "routeGeneration": 1, "sha256": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}""", Encoding.UTF8, "application/json");using var response = await client.SendAsync(request);var text = await response.Content.ReadAsStringAsync();if (!response.IsSuccessStatusCode) throw new HttpRequestException($"HTTP {(int)response.StatusCode}: {text}");Console.WriteLine($"{(int)response.StatusCode} {text}");响应字段 · 200
assetIdstring必填chunkSizeinteger · int64必填分片大小(字节);0 表示整文件直传
cosobject可选腾讯云 COS STS 临时密钥(仅 Web SPA 直传 COS 时返回)
展开字段 / 类型
bucketstring必填COS 存储桶名称(含 APPID,如 bucket-1250000000)
expiredTimeinteger · int64必填临时密钥过期时间戳(秒)
keystring必填包含存储前缀的完整对象路径
regionstring必填COS 地域(如 ap-guangzhou)
sessionTokenstring必填STS 临时安全令牌 XCosSecurityToken
startTimeinteger · int64必填临时密钥生效时间戳(秒)
tmpSecretIdstring必填STS 临时 SecretId
tmpSecretKeystring必填STS 临时 SecretKey
estimatedQueueSecondsinteger · int64可选目标节点预估排队秒数
expiresAtstring · date-time必填fileFieldstring | null必填method 为 POST(表单上传)时文件所在的字段名;PUT 为 null
formFieldsstring[][]可选表单 POST 直传对象存储时附带的签名字段
展开字段 / 类型
stringheadersstring[][]必填展开字段 / 类型
stringmethod"PUT" | "POST"必填nodeIdstring可选直传节点 ID
routestring可选上传路径:node_direct 或 object_store
routeGenerationinteger · int64可选上传会话代次
status"pending" | "preparing" | "ready" | "failed"可选pending可上传;幂等恢复返回preparing/ready时uploadUrl为空,不应重传
uploadUrlstring必填
存储上传成功后,使用凭证中的 assetId 调用 complete。服务端检查对象是否存在、实际字节数,再持久化媒体核验任务;核验尺寸、时长与完整性通过后才变为 ready。不能只凭客户端上传成功声明入库。此接口幂等,响应丢失可以重试。
complete 可能返回 preparing,这表示文件仍在核验。使用下面的状态接口等待 ready 后再报价或提交处理;failed 为终态,读取 errorCode/error 后重新上传修正后的文件。状态接口也能查询 pending,无需让客户端反复生成下载链接。建议间隔 15 秒查询。
/api/v1/assets/{assetId}/complete路径、查询与请求头
| 参数 | 位置 | 类型与约束 |
|---|---|---|
assetId必填 | path | string素材 ID |
请求体字段 · application/json
partsobject[]可选maxItems: 1024
展开字段 / 类型
etagstring可选maxLength: 256
numberinteger · int64必填minimum: 1 · maximum: 1024
sha256string可选maxLength: 64
routeGenerationinteger · int64可选minimum: 1
调用示例
curl --include --fail-with-body --silent --show-error --max-time 60 \ --request POST 'https://www.chaozapi.com/api/v1/assets/ASSET_ID/complete' \ --header "Authorization: Bearer $GLACIER_API_KEY"// Node.js 22+; save as example.mjs, then: node example.mjsconst key = process.env.GLACIER_API_KEY;if (!key) throw new Error('Set GLACIER_API_KEY');const response = await fetch('https://www.chaozapi.com/api/v1/assets/ASSET_ID/complete', { method: 'POST', headers: { Authorization: `Bearer ${key}`, }, signal: AbortSignal.timeout(60_000),});const text = await response.text();if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);console.log(response.status, text);# Python 3.10+; standard library; python example.pyimport osimport urllib.requestimport urllib.error
headers = {"Authorization": "Bearer " + os.environ["GLACIER_API_KEY"]}request = urllib.request.Request( "https://www.chaozapi.com/api/v1/assets/ASSET_ID/complete", method="POST", headers=headers,)try: with urllib.request.urlopen(request, timeout=60) as response: print(response.status, response.read().decode("utf-8"))except urllib.error.HTTPError as error: raise RuntimeError(f"HTTP {error.code}: {error.read().decode('utf-8')}") from error// Go 1.22+; go run example.gopackage main
import ( "fmt" "io" "net/http" "os" "time")
func main() { key := os.Getenv("GLACIER_API_KEY") if key == "" { panic("Set GLACIER_API_KEY") } req, err := http.NewRequest("POST", "https://www.chaozapi.com/api/v1/assets/ASSET_ID/complete", nil) if err != nil { panic(err) } req.Header.Set("Authorization", "Bearer " + key) client := &http.Client{Timeout: 60 * time.Second} res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() data, err := io.ReadAll(res.Body) if err != nil { panic(err) } if res.StatusCode >= 300 { panic(fmt.Sprintf("HTTP %d: %s", res.StatusCode, data)) } fmt.Println(res.StatusCode, string(data))}// cargo add reqwest@0.13 --features blocking// Save in src/main.rs, then: cargo runuse std::{env, error::Error, time::Duration};
fn main() -> Result<(), Box<dyn Error>> { let client = reqwest::blocking::Client::builder() .timeout(Duration::from_secs(60)).build()?; let response = client.request(reqwest::Method::POST, "https://www.chaozapi.com/api/v1/assets/ASSET_ID/complete") .bearer_auth(env::var("GLACIER_API_KEY")?) .send()?; let status = response.status(); let text = response.text()?; if !status.is_success() { return Err(format!("HTTP {status}: {text}").into()); } println!("{status} {text}"); Ok(())}// Java 17+; save as Example.java, then: java Example.javaimport java.net.URI;import java.net.http.*;import java.time.Duration;import java.util.Objects;
class Example { public static void main(String[] args) throws Exception { var key = Objects.requireNonNull(System.getenv("GLACIER_API_KEY")); var client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build(); var request = HttpRequest.newBuilder(URI.create("https://www.chaozapi.com/api/v1/assets/ASSET_ID/complete")) .timeout(Duration.ofSeconds(60)) .header("Authorization", "Bearer " + key) .method("POST", HttpRequest.BodyPublishers.noBody()) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() >= 300) throw new IllegalStateException("HTTP " + response.statusCode() + ": " + response.body()); System.out.println(response.statusCode() + " " + response.body()); }}// .NET 8+; dotnet new console; replace Program.cs; dotnet runusing System;using System.Net.Http;using System.Net.Http.Headers;using System.Text;
var key = Environment.GetEnvironmentVariable("GLACIER_API_KEY") ?? throw new InvalidOperationException("Set GLACIER_API_KEY");using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://www.chaozapi.com/api/v1/assets/ASSET_ID/complete");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);using var response = await client.SendAsync(request);var text = await response.Content.ReadAsStringAsync();if (!response.IsSuccessStatusCode) throw new HttpRequestException($"HTTP {(int)response.StatusCode}: {text}");Console.WriteLine($"{(int)response.StatusCode} {text}");响应字段 · 200
coverUrlstring | null必填视频封面(上传时截取的原件首帧 JPEG,长边不超过 1920);图片或截取失败时为 null
createdAtstring · date-time必填durationMsinteger | null · int64必填视频与动图有值(动图为各帧时长之和)
expiresAtstring | null · date-time必填素材保留期限;null 表示沿用原保留规则
heightinteger · int64必填idstring必填isPublicboolean必填公共素材(示范素材):所有用户可见、不可删除;对它发起处理时自动复制到个人素材库,任务的 assetId 为副本
kind"image" | "video"必填mimeTypestring必填namestring必填prepareErrorstring可选入库失败原因
sizeBytesinteger · int64必填status"pending" | "preparing" | "ready" | "failed"必填素材状态:ready 可直接使用;preparing 表示入库探测中
thumbnailUrlstring | null必填updatedAtstring · date-time必填urlstring必填原件地址(已签名;列表接口对视频仅签发缩略图/封面时可为空串)
versionCountinteger · int64必填现存版本数(含原件;删除的版本不计)
widthinteger · int64必填
响应头: Retry-After
/api/v1/assets/{assetId}/upload-status路径、查询与请求头
| 参数 | 位置 | 类型与约束 |
|---|---|---|
assetId必填 | path | string素材 ID |
调用示例
curl --include --fail-with-body --silent --show-error --max-time 60 \ --request GET 'https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-status' \ --header "Authorization: Bearer $GLACIER_API_KEY"// Node.js 22+; save as example.mjs, then: node example.mjsconst key = process.env.GLACIER_API_KEY;if (!key) throw new Error('Set GLACIER_API_KEY');const response = await fetch('https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-status', { method: 'GET', headers: { Authorization: `Bearer ${key}`, }, signal: AbortSignal.timeout(60_000),});const text = await response.text();if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);console.log(response.status, text);# Python 3.10+; standard library; python example.pyimport osimport urllib.requestimport urllib.error
headers = {"Authorization": "Bearer " + os.environ["GLACIER_API_KEY"]}request = urllib.request.Request( "https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-status", method="GET", headers=headers,)try: with urllib.request.urlopen(request, timeout=60) as response: print(response.status, response.read().decode("utf-8"))except urllib.error.HTTPError as error: raise RuntimeError(f"HTTP {error.code}: {error.read().decode('utf-8')}") from error// Go 1.22+; go run example.gopackage main
import ( "fmt" "io" "net/http" "os" "time")
func main() { key := os.Getenv("GLACIER_API_KEY") if key == "" { panic("Set GLACIER_API_KEY") } req, err := http.NewRequest("GET", "https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-status", nil) if err != nil { panic(err) } req.Header.Set("Authorization", "Bearer " + key) client := &http.Client{Timeout: 60 * time.Second} res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() data, err := io.ReadAll(res.Body) if err != nil { panic(err) } if res.StatusCode >= 300 { panic(fmt.Sprintf("HTTP %d: %s", res.StatusCode, data)) } fmt.Println(res.StatusCode, string(data))}// cargo add reqwest@0.13 --features blocking// Save in src/main.rs, then: cargo runuse std::{env, error::Error, time::Duration};
fn main() -> Result<(), Box<dyn Error>> { let client = reqwest::blocking::Client::builder() .timeout(Duration::from_secs(60)).build()?; let response = client.request(reqwest::Method::GET, "https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-status") .bearer_auth(env::var("GLACIER_API_KEY")?) .send()?; let status = response.status(); let text = response.text()?; if !status.is_success() { return Err(format!("HTTP {status}: {text}").into()); } println!("{status} {text}"); Ok(())}// Java 17+; save as Example.java, then: java Example.javaimport java.net.URI;import java.net.http.*;import java.time.Duration;import java.util.Objects;
class Example { public static void main(String[] args) throws Exception { var key = Objects.requireNonNull(System.getenv("GLACIER_API_KEY")); var client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build(); var request = HttpRequest.newBuilder(URI.create("https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-status")) .timeout(Duration.ofSeconds(60)) .header("Authorization", "Bearer " + key) .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() >= 300) throw new IllegalStateException("HTTP " + response.statusCode() + ": " + response.body()); System.out.println(response.statusCode() + " " + response.body()); }}// .NET 8+; dotnet new console; replace Program.cs; dotnet runusing System;using System.Net.Http;using System.Net.Http.Headers;using System.Text;
var key = Environment.GetEnvironmentVariable("GLACIER_API_KEY") ?? throw new InvalidOperationException("Set GLACIER_API_KEY");using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://www.chaozapi.com/api/v1/assets/ASSET_ID/upload-status");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);using var response = await client.SendAsync(request);var text = await response.Content.ReadAsStringAsync();if (!response.IsSuccessStatusCode) throw new HttpRequestException($"HTTP {(int)response.StatusCode}: {text}");Console.WriteLine($"{(int)response.StatusCode} {text}");响应字段 · 200
assetIdstring必填errorstring | null必填errorCodestring | null必填status"pending" | "preparing" | "ready" | "failed"必填
列表与分页
“列表与分页”章节scope=mine 只查询自己的素材,scope=public 查询示范素材,默认 scope=all。可用 kind、search 筛选。把返回的 nextCursor 作为下一页的 cursor 参数,直到它为 null。示例每页查询 24 条。
素材列表包含 preparing/ready,不包含 pending/failed。保存 assetId 或上传幂等键,以恢复未完成的上传。
/api/v1/assets路径、查询与请求头
| 参数 | 位置 | 类型与约束 |
|---|---|---|
scope可选 | query | "all" | "mine" | "public"不传 = all:公共素材在前,然后是我的素材 |
kind可选 | query | "image" | "video"不传 = 全部类型 |
search可选 | query | string按名称模糊搜索 maxLength: 100 |
limit可选 | query | integer · int64minimum: 1 · maximum: 100 · default: 24 |
cursor可选 | query | string上一页返回的 nextCursor |
调用示例
curl --include --fail-with-body --silent --show-error --max-time 60 \ --request GET 'https://www.chaozapi.com/api/v1/assets?scope=mine&limit=24' \ --header "Authorization: Bearer $GLACIER_API_KEY"// Node.js 22+; save as example.mjs, then: node example.mjsconst key = process.env.GLACIER_API_KEY;if (!key) throw new Error('Set GLACIER_API_KEY');const response = await fetch('https://www.chaozapi.com/api/v1/assets?scope=mine&limit=24', { method: 'GET', headers: { Authorization: `Bearer ${key}`, }, signal: AbortSignal.timeout(60_000),});const text = await response.text();if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);console.log(response.status, text);# Python 3.10+; standard library; python example.pyimport osimport urllib.requestimport urllib.error
headers = {"Authorization": "Bearer " + os.environ["GLACIER_API_KEY"]}request = urllib.request.Request( "https://www.chaozapi.com/api/v1/assets?scope=mine&limit=24", method="GET", headers=headers,)try: with urllib.request.urlopen(request, timeout=60) as response: print(response.status, response.read().decode("utf-8"))except urllib.error.HTTPError as error: raise RuntimeError(f"HTTP {error.code}: {error.read().decode('utf-8')}") from error// Go 1.22+; go run example.gopackage main
import ( "fmt" "io" "net/http" "os" "time")
func main() { key := os.Getenv("GLACIER_API_KEY") if key == "" { panic("Set GLACIER_API_KEY") } req, err := http.NewRequest("GET", "https://www.chaozapi.com/api/v1/assets?scope=mine&limit=24", nil) if err != nil { panic(err) } req.Header.Set("Authorization", "Bearer " + key) client := &http.Client{Timeout: 60 * time.Second} res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() data, err := io.ReadAll(res.Body) if err != nil { panic(err) } if res.StatusCode >= 300 { panic(fmt.Sprintf("HTTP %d: %s", res.StatusCode, data)) } fmt.Println(res.StatusCode, string(data))}// cargo add reqwest@0.13 --features blocking// Save in src/main.rs, then: cargo runuse std::{env, error::Error, time::Duration};
fn main() -> Result<(), Box<dyn Error>> { let client = reqwest::blocking::Client::builder() .timeout(Duration::from_secs(60)).build()?; let response = client.request(reqwest::Method::GET, "https://www.chaozapi.com/api/v1/assets?scope=mine&limit=24") .bearer_auth(env::var("GLACIER_API_KEY")?) .send()?; let status = response.status(); let text = response.text()?; if !status.is_success() { return Err(format!("HTTP {status}: {text}").into()); } println!("{status} {text}"); Ok(())}// Java 17+; save as Example.java, then: java Example.javaimport java.net.URI;import java.net.http.*;import java.time.Duration;import java.util.Objects;
class Example { public static void main(String[] args) throws Exception { var key = Objects.requireNonNull(System.getenv("GLACIER_API_KEY")); var client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build(); var request = HttpRequest.newBuilder(URI.create("https://www.chaozapi.com/api/v1/assets?scope=mine&limit=24")) .timeout(Duration.ofSeconds(60)) .header("Authorization", "Bearer " + key) .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() >= 300) throw new IllegalStateException("HTTP " + response.statusCode() + ": " + response.body()); System.out.println(response.statusCode() + " " + response.body()); }}// .NET 8+; dotnet new console; replace Program.cs; dotnet runusing System;using System.Net.Http;using System.Net.Http.Headers;using System.Text;
var key = Environment.GetEnvironmentVariable("GLACIER_API_KEY") ?? throw new InvalidOperationException("Set GLACIER_API_KEY");using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://www.chaozapi.com/api/v1/assets?scope=mine&limit=24");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);using var response = await client.SendAsync(request);var text = await response.Content.ReadAsStringAsync();if (!response.IsSuccessStatusCode) throw new HttpRequestException($"HTTP {(int)response.StatusCode}: {text}");Console.WriteLine($"{(int)response.StatusCode} {text}");响应字段 · 200
itemsobject[]必填展开字段 / 类型
coverUrlstring | null必填视频封面(上传时截取的原件首帧 JPEG,长边不超过 1920);图片或截取失败时为 null
createdAtstring · date-time必填durationMsinteger | null · int64必填视频与动图有值(动图为各帧时长之和)
expiresAtstring | null · date-time必填素材保留期限;null 表示沿用原保留规则
heightinteger · int64必填idstring必填isPublicboolean必填公共素材(示范素材):所有用户可见、不可删除;对它发起处理时自动复制到个人素材库,任务的 assetId 为副本
kind"image" | "video"必填mimeTypestring必填namestring必填prepareErrorstring可选入库失败原因
sizeBytesinteger · int64必填status"pending" | "preparing" | "ready" | "failed"必填素材状态:ready 可直接使用;preparing 表示入库探测中
thumbnailUrlstring | null必填updatedAtstring · date-time必填urlstring必填原件地址(已签名;列表接口对视频仅签发缩略图/封面时可为空串)
versionCountinteger · int64必填现存版本数(含原件;删除的版本不计)
widthinteger · int64必填
nextCursorstring | null必填totalinteger · int64必填
查询素材与版本
“查询素材与版本”章节响应包含 asset 和 versions。如需以某个处理版本继续加工,保留它的版本 ID,作为后续任务的 sourceVersionId。文件地址是临时链接,需要时重新查询获取。处理公共素材时可能生成个人副本,后续以任务返回的 assetId 为准。
/api/v1/assets/{assetId}路径、查询与请求头
| 参数 | 位置 | 类型与约束 |
|---|---|---|
assetId必填 | path | string素材 ID |
调用示例
curl --include --fail-with-body --silent --show-error --max-time 60 \ --request GET 'https://www.chaozapi.com/api/v1/assets/ASSET_ID' \ --header "Authorization: Bearer $GLACIER_API_KEY"// Node.js 22+; save as example.mjs, then: node example.mjsconst key = process.env.GLACIER_API_KEY;if (!key) throw new Error('Set GLACIER_API_KEY');const response = await fetch('https://www.chaozapi.com/api/v1/assets/ASSET_ID', { method: 'GET', headers: { Authorization: `Bearer ${key}`, }, signal: AbortSignal.timeout(60_000),});const text = await response.text();if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);console.log(response.status, text);# Python 3.10+; standard library; python example.pyimport osimport urllib.requestimport urllib.error
headers = {"Authorization": "Bearer " + os.environ["GLACIER_API_KEY"]}request = urllib.request.Request( "https://www.chaozapi.com/api/v1/assets/ASSET_ID", method="GET", headers=headers,)try: with urllib.request.urlopen(request, timeout=60) as response: print(response.status, response.read().decode("utf-8"))except urllib.error.HTTPError as error: raise RuntimeError(f"HTTP {error.code}: {error.read().decode('utf-8')}") from error// Go 1.22+; go run example.gopackage main
import ( "fmt" "io" "net/http" "os" "time")
func main() { key := os.Getenv("GLACIER_API_KEY") if key == "" { panic("Set GLACIER_API_KEY") } req, err := http.NewRequest("GET", "https://www.chaozapi.com/api/v1/assets/ASSET_ID", nil) if err != nil { panic(err) } req.Header.Set("Authorization", "Bearer " + key) client := &http.Client{Timeout: 60 * time.Second} res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() data, err := io.ReadAll(res.Body) if err != nil { panic(err) } if res.StatusCode >= 300 { panic(fmt.Sprintf("HTTP %d: %s", res.StatusCode, data)) } fmt.Println(res.StatusCode, string(data))}// cargo add reqwest@0.13 --features blocking// Save in src/main.rs, then: cargo runuse std::{env, error::Error, time::Duration};
fn main() -> Result<(), Box<dyn Error>> { let client = reqwest::blocking::Client::builder() .timeout(Duration::from_secs(60)).build()?; let response = client.request(reqwest::Method::GET, "https://www.chaozapi.com/api/v1/assets/ASSET_ID") .bearer_auth(env::var("GLACIER_API_KEY")?) .send()?; let status = response.status(); let text = response.text()?; if !status.is_success() { return Err(format!("HTTP {status}: {text}").into()); } println!("{status} {text}"); Ok(())}// Java 17+; save as Example.java, then: java Example.javaimport java.net.URI;import java.net.http.*;import java.time.Duration;import java.util.Objects;
class Example { public static void main(String[] args) throws Exception { var key = Objects.requireNonNull(System.getenv("GLACIER_API_KEY")); var client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build(); var request = HttpRequest.newBuilder(URI.create("https://www.chaozapi.com/api/v1/assets/ASSET_ID")) .timeout(Duration.ofSeconds(60)) .header("Authorization", "Bearer " + key) .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() >= 300) throw new IllegalStateException("HTTP " + response.statusCode() + ": " + response.body()); System.out.println(response.statusCode() + " " + response.body()); }}// .NET 8+; dotnet new console; replace Program.cs; dotnet runusing System;using System.Net.Http;using System.Net.Http.Headers;using System.Text;
var key = Environment.GetEnvironmentVariable("GLACIER_API_KEY") ?? throw new InvalidOperationException("Set GLACIER_API_KEY");using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://www.chaozapi.com/api/v1/assets/ASSET_ID");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);using var response = await client.SendAsync(request);var text = await response.Content.ReadAsStringAsync();if (!response.IsSuccessStatusCode) throw new HttpRequestException($"HTTP {(int)response.StatusCode}: {text}");Console.WriteLine($"{(int)response.StatusCode} {text}");响应字段 · 200
assetobject必填展开字段 / 类型
coverUrlstring | null必填视频封面(上传时截取的原件首帧 JPEG,长边不超过 1920);图片或截取失败时为 null
createdAtstring · date-time必填durationMsinteger | null · int64必填视频与动图有值(动图为各帧时长之和)
expiresAtstring | null · date-time必填素材保留期限;null 表示沿用原保留规则
heightinteger · int64必填idstring必填isPublicboolean必填公共素材(示范素材):所有用户可见、不可删除;对它发起处理时自动复制到个人素材库,任务的 assetId 为副本
kind"image" | "video"必填mimeTypestring必填namestring必填prepareErrorstring可选入库失败原因
sizeBytesinteger · int64必填status"pending" | "preparing" | "ready" | "failed"必填素材状态:ready 可直接使用;preparing 表示入库探测中
thumbnailUrlstring | null必填updatedAtstring · date-time必填urlstring必填原件地址(已签名;列表接口对视频仅签发缩略图/封面时可为空串)
versionCountinteger · int64必填现存版本数(含原件;删除的版本不计)
widthinteger · int64必填
versionsobject[]必填展开字段 / 类型
assetIdstring必填createdAtstring · date-time必填downloadUrlstring必填下载地址(响应带 Content-Disposition: attachment,文件名形如 原名_V2_超分.mp4)
durationMsinteger | null · int64必填视频与动图有值(动图为各帧时长之和)
frameCountinteger | null · int64必填帧数,视频与动图有值(图片的 frameCount > 1 即动图,按帧计费);旧版本为 null
frameRatenumber | null · double必填平均帧率(帧/秒),视频与动图有值(动图各帧时长不同,只用于展示);旧版本为 null
heightinteger · int64必填idstring必填indexinteger · int64必填版本号,0 = 原件;只增不减,删除过的版本号不复用(版本列表可能不连续)
labelstring必填maskUrlstring | null必填去水印的识别遮罩视频(H.264,与输入版本 sourceVersionId 按时间对齐,亮 = 被修复的像素,分辨率可能低于原视频),前端对比时叠加在原视频上;其他版本为 null
mimeTypestring必填previewPendingboolean必填预览正在后台转码,完成后 previewUrl 才有值;期间可轮询 getAsset
previewUrlstring | null必填浏览器可播放的 H.264 预览;为 null 时直接播放 url(原视频浏览器可播放、图片、转码失败)
sizeBytesinteger · int64必填sourceVersionIdstring | null必填由哪个版本处理而来(前端默认与它对比);原件为 null;该版本可能已被删除
thumbnailUrlstring | null必填toolIdstring | null必填urlstring必填原始文件地址(已签名)
watermarkMarksobject[]必填用户在这个版本上的去水印标记(随版本保存,下次打开继续编辑);没有为空数组
展开字段 / 类型
colorstring可选纯色水印的颜色(#rrggbb,如白字 #ffffff);不填表示不按颜色收紧遮罩
pattern: "^#[0-9a-fA-F]{6}$"
endMsinteger · int64可选作用区间的结束时间(毫秒,含),须带 timeMs 且不早于它;不填表示只作用于 timeMs 这一帧。positive 带 endMs 表示确认这一段要修复
minimum: 0
heightnumber · double必填高度(占画面高度的比例)
minimum: 0 · maximum: 1
kind"positive" | "negative" | "absent" | "suggested"可选标记类型:positive(默认)这里有水印;negative 减选,这里不是水印;absent 这一段没有这个水印(须带 objectId);suggested 自动查找的建议,用户确认(改成 positive)前不参与识别
objectIdinteger · int64可选水印编号(前端同一种颜色):同一编号在不同时间点的标记是同一个水印,各自向前后跟踪到彼此相遇;不填表示每处标记各是一个水印
minimum: 0 · maximum: 7
strokesobject[]可选涂抹的画笔轨迹;为空表示框选(整个框都是水印)
maxItems: 64
展开字段 / 类型
pointsnumber · double[][]必填轨迹点 [x, y](相对画面)
minItems: 1 · maxItems: 4000
展开字段 / 类型
number · doubleradiusnumber · double必填画笔半径(占画面宽度的比例)
minimum: 0 · maximum: 0.25
timeMsinteger · int64可选标记时的视频时间点(毫秒);不填表示整段视频固定位置
minimum: 0
widthnumber · double必填宽度(占画面宽度的比例)
minimum: 0 · maximum: 1
xnumber · double必填左边缘(占画面宽度的比例)
minimum: 0 · maximum: 1
ynumber · double必填上边缘(占画面高度的比例)
minimum: 0 · maximum: 1
watermarkObjectsobject[]必填用户给这个版本上各个水印起的名字;没有为空数组(前端显示「水印 n」)
展开字段 / 类型
namestring必填水印名称
minLength: 1 · maxLength: 24
objectIdinteger · int64必填minimum: 0 · maximum: 7
widthinteger · int64必填
按需获取版本下载链接
“按需获取版本下载链接”章节在实际发起文件下载前,按需为指定版本签发短时下载链接(返回临时 url、文件名、大小、sha256、locationVersion 与过期时间)。服务会根据当前副本热窗与节点健康状态自动选择最优下载源。
此接口只需要 read 权限。临时链接过期与素材 expiresAt 保留期限不同:前者可以刷新,后者到期清理后不能恢复。下载时不要携带 API Key,也不要解析或固定存储域名。
/api/v1/assets/{assetId}/versions/{versionId}/download-url路径、查询与请求头
| 参数 | 位置 | 类型与约束 |
|---|---|---|
assetId必填 | path | string素材 ID |
versionId必填 | path | string版本 ID |
调用示例
curl --include --fail-with-body --silent --show-error --max-time 60 \ --request POST 'https://www.chaozapi.com/api/v1/assets/ASSET_ID/versions/VERSION_ID/download-url' \ --header "Authorization: Bearer $GLACIER_API_KEY"// Node.js 22+; save as example.mjs, then: node example.mjsconst key = process.env.GLACIER_API_KEY;if (!key) throw new Error('Set GLACIER_API_KEY');const response = await fetch('https://www.chaozapi.com/api/v1/assets/ASSET_ID/versions/VERSION_ID/download-url', { method: 'POST', headers: { Authorization: `Bearer ${key}`, }, signal: AbortSignal.timeout(60_000),});const text = await response.text();if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);console.log(response.status, text);# Python 3.10+; standard library; python example.pyimport osimport urllib.requestimport urllib.error
headers = {"Authorization": "Bearer " + os.environ["GLACIER_API_KEY"]}request = urllib.request.Request( "https://www.chaozapi.com/api/v1/assets/ASSET_ID/versions/VERSION_ID/download-url", method="POST", headers=headers,)try: with urllib.request.urlopen(request, timeout=60) as response: print(response.status, response.read().decode("utf-8"))except urllib.error.HTTPError as error: raise RuntimeError(f"HTTP {error.code}: {error.read().decode('utf-8')}") from error// Go 1.22+; go run example.gopackage main
import ( "fmt" "io" "net/http" "os" "time")
func main() { key := os.Getenv("GLACIER_API_KEY") if key == "" { panic("Set GLACIER_API_KEY") } req, err := http.NewRequest("POST", "https://www.chaozapi.com/api/v1/assets/ASSET_ID/versions/VERSION_ID/download-url", nil) if err != nil { panic(err) } req.Header.Set("Authorization", "Bearer " + key) client := &http.Client{Timeout: 60 * time.Second} res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() data, err := io.ReadAll(res.Body) if err != nil { panic(err) } if res.StatusCode >= 300 { panic(fmt.Sprintf("HTTP %d: %s", res.StatusCode, data)) } fmt.Println(res.StatusCode, string(data))}// cargo add reqwest@0.13 --features blocking// Save in src/main.rs, then: cargo runuse std::{env, error::Error, time::Duration};
fn main() -> Result<(), Box<dyn Error>> { let client = reqwest::blocking::Client::builder() .timeout(Duration::from_secs(60)).build()?; let response = client.request(reqwest::Method::POST, "https://www.chaozapi.com/api/v1/assets/ASSET_ID/versions/VERSION_ID/download-url") .bearer_auth(env::var("GLACIER_API_KEY")?) .send()?; let status = response.status(); let text = response.text()?; if !status.is_success() { return Err(format!("HTTP {status}: {text}").into()); } println!("{status} {text}"); Ok(())}// Java 17+; save as Example.java, then: java Example.javaimport java.net.URI;import java.net.http.*;import java.time.Duration;import java.util.Objects;
class Example { public static void main(String[] args) throws Exception { var key = Objects.requireNonNull(System.getenv("GLACIER_API_KEY")); var client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build(); var request = HttpRequest.newBuilder(URI.create("https://www.chaozapi.com/api/v1/assets/ASSET_ID/versions/VERSION_ID/download-url")) .timeout(Duration.ofSeconds(60)) .header("Authorization", "Bearer " + key) .method("POST", HttpRequest.BodyPublishers.noBody()) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() >= 300) throw new IllegalStateException("HTTP " + response.statusCode() + ": " + response.body()); System.out.println(response.statusCode() + " " + response.body()); }}// .NET 8+; dotnet new console; replace Program.cs; dotnet runusing System;using System.Net.Http;using System.Net.Http.Headers;using System.Text;
var key = Environment.GetEnvironmentVariable("GLACIER_API_KEY") ?? throw new InvalidOperationException("Set GLACIER_API_KEY");using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://www.chaozapi.com/api/v1/assets/ASSET_ID/versions/VERSION_ID/download-url");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);using var response = await client.SendAsync(request);var text = await response.Content.ReadAsStringAsync();if (!response.IsSuccessStatusCode) throw new HttpRequestException($"HTTP {(int)response.StatusCode}: {text}");Console.WriteLine($"{(int)response.StatusCode} {text}");响应字段 · 200
expiresAtstring · date-time必填filenamestring必填locationVersioninteger · int64必填mimeTypestring必填sha256string必填sizeBytesinteger · int64必填urlstring必填实时按需签发的短有效期下载链接(含 Content-Disposition: attachment)
响应头: Cache-Control
重命名素材
“重命名素材”章节仅修改传入的字段。名称会去掉首尾空白,可以与其他素材重名。
/api/v1/assets/{assetId}路径、查询与请求头
| 参数 | 位置 | 类型与约束 |
|---|---|---|
assetId必填 | path | string素材 ID |
请求体字段 · application/json
namestring可选素材名称(首尾空白会去掉);可与其他素材重名
minLength: 1 · maxLength: 255
调用示例
curl --include --fail-with-body --silent --show-error --max-time 60 \ --request PATCH 'https://www.chaozapi.com/api/v1/assets/ASSET_ID' \ --header "Authorization: Bearer $GLACIER_API_KEY" \ --header 'Content-Type: application/json' \ --data-raw '{ "name": "Enhanced photo"}'// Node.js 22+; save as example.mjs, then: node example.mjsconst key = process.env.GLACIER_API_KEY;if (!key) throw new Error('Set GLACIER_API_KEY');const response = await fetch('https://www.chaozapi.com/api/v1/assets/ASSET_ID', { method: 'PATCH', headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ "name": "Enhanced photo"}), signal: AbortSignal.timeout(60_000),});const text = await response.text();if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);console.log(response.status, text);# Python 3.10+; standard library; python example.pyimport osimport urllib.requestimport urllib.error
headers = {"Authorization": "Bearer " + os.environ["GLACIER_API_KEY"]}headers["Content-Type"] = "application/json"request = urllib.request.Request( "https://www.chaozapi.com/api/v1/assets/ASSET_ID", method="PATCH", headers=headers, data="""{ "name": "Enhanced photo"}""".encode("utf-8"),)try: with urllib.request.urlopen(request, timeout=60) as response: print(response.status, response.read().decode("utf-8"))except urllib.error.HTTPError as error: raise RuntimeError(f"HTTP {error.code}: {error.read().decode('utf-8')}") from error// Go 1.22+; go run example.gopackage main
import ( "fmt" "io" "net/http" "os" "strings" "time")
func main() { key := os.Getenv("GLACIER_API_KEY") if key == "" { panic("Set GLACIER_API_KEY") } req, err := http.NewRequest("PATCH", "https://www.chaozapi.com/api/v1/assets/ASSET_ID", strings.NewReader(`{ "name": "Enhanced photo"}`)) if err != nil { panic(err) } req.Header.Set("Authorization", "Bearer " + key) req.Header.Set("Content-Type", "application/json") client := &http.Client{Timeout: 60 * time.Second} res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() data, err := io.ReadAll(res.Body) if err != nil { panic(err) } if res.StatusCode >= 300 { panic(fmt.Sprintf("HTTP %d: %s", res.StatusCode, data)) } fmt.Println(res.StatusCode, string(data))}// cargo add reqwest@0.13 --features blocking// Save in src/main.rs, then: cargo runuse std::{env, error::Error, time::Duration};
fn main() -> Result<(), Box<dyn Error>> { let client = reqwest::blocking::Client::builder() .timeout(Duration::from_secs(60)).build()?; let response = client.request(reqwest::Method::PATCH, "https://www.chaozapi.com/api/v1/assets/ASSET_ID") .bearer_auth(env::var("GLACIER_API_KEY")?) .header("Content-Type", "application/json") .body(r#"{ "name": "Enhanced photo"}"#) .send()?; let status = response.status(); let text = response.text()?; if !status.is_success() { return Err(format!("HTTP {status}: {text}").into()); } println!("{status} {text}"); Ok(())}// Java 17+; save as Example.java, then: java Example.javaimport java.net.URI;import java.net.http.*;import java.time.Duration;import java.util.Objects;
class Example { public static void main(String[] args) throws Exception { var key = Objects.requireNonNull(System.getenv("GLACIER_API_KEY")); var client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build(); var request = HttpRequest.newBuilder(URI.create("https://www.chaozapi.com/api/v1/assets/ASSET_ID")) .timeout(Duration.ofSeconds(60)) .header("Authorization", "Bearer " + key) .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString("""{ "name": "Enhanced photo"}""")) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() >= 300) throw new IllegalStateException("HTTP " + response.statusCode() + ": " + response.body()); System.out.println(response.statusCode() + " " + response.body()); }}// .NET 8+; dotnet new console; replace Program.cs; dotnet runusing System;using System.Net.Http;using System.Net.Http.Headers;using System.Text;
var key = Environment.GetEnvironmentVariable("GLACIER_API_KEY") ?? throw new InvalidOperationException("Set GLACIER_API_KEY");using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };using var request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://www.chaozapi.com/api/v1/assets/ASSET_ID");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);request.Content = new StringContent("""{ "name": "Enhanced photo"}""", Encoding.UTF8, "application/json");using var response = await client.SendAsync(request);var text = await response.Content.ReadAsStringAsync();if (!response.IsSuccessStatusCode) throw new HttpRequestException($"HTTP {(int)response.StatusCode}: {text}");Console.WriteLine($"{(int)response.StatusCode} {text}");响应字段 · 200
coverUrlstring | null必填视频封面(上传时截取的原件首帧 JPEG,长边不超过 1920);图片或截取失败时为 null
createdAtstring · date-time必填durationMsinteger | null · int64必填视频与动图有值(动图为各帧时长之和)
expiresAtstring | null · date-time必填素材保留期限;null 表示沿用原保留规则
heightinteger · int64必填idstring必填isPublicboolean必填公共素材(示范素材):所有用户可见、不可删除;对它发起处理时自动复制到个人素材库,任务的 assetId 为副本
kind"image" | "video"必填mimeTypestring必填namestring必填prepareErrorstring可选入库失败原因
sizeBytesinteger · int64必填status"pending" | "preparing" | "ready" | "failed"必填素材状态:ready 可直接使用;preparing 表示入库探测中
thumbnailUrlstring | null必填updatedAtstring · date-time必填urlstring必填原件地址(已签名;列表接口对视频仅签发缩略图/封面时可为空串)
versionCountinteger · int64必填现存版本数(含原件;删除的版本不计)
widthinteger · int64必填
删除处理版本
“删除处理版本”章节删除某个处理结果版本,不能通过此接口删除原件;删除原件需要删除整个素材。成功返回 204,没有响应正文。
/api/v1/assets/{assetId}/versions/{versionId}路径、查询与请求头
| 参数 | 位置 | 类型与约束 |
|---|---|---|
assetId必填 | path | string素材 ID |
versionId必填 | path | string版本 ID |
调用示例
curl --include --fail-with-body --silent --show-error --max-time 60 \ --request DELETE 'https://www.chaozapi.com/api/v1/assets/ASSET_ID/versions/VERSION_ID' \ --header "Authorization: Bearer $GLACIER_API_KEY"// Node.js 22+; save as example.mjs, then: node example.mjsconst key = process.env.GLACIER_API_KEY;if (!key) throw new Error('Set GLACIER_API_KEY');const response = await fetch('https://www.chaozapi.com/api/v1/assets/ASSET_ID/versions/VERSION_ID', { method: 'DELETE', headers: { Authorization: `Bearer ${key}`, }, signal: AbortSignal.timeout(60_000),});const text = await response.text();if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);console.log(response.status, text);# Python 3.10+; standard library; python example.pyimport osimport urllib.requestimport urllib.error
headers = {"Authorization": "Bearer " + os.environ["GLACIER_API_KEY"]}request = urllib.request.Request( "https://www.chaozapi.com/api/v1/assets/ASSET_ID/versions/VERSION_ID", method="DELETE", headers=headers,)try: with urllib.request.urlopen(request, timeout=60) as response: print(response.status, response.read().decode("utf-8"))except urllib.error.HTTPError as error: raise RuntimeError(f"HTTP {error.code}: {error.read().decode('utf-8')}") from error// Go 1.22+; go run example.gopackage main
import ( "fmt" "io" "net/http" "os" "time")
func main() { key := os.Getenv("GLACIER_API_KEY") if key == "" { panic("Set GLACIER_API_KEY") } req, err := http.NewRequest("DELETE", "https://www.chaozapi.com/api/v1/assets/ASSET_ID/versions/VERSION_ID", nil) if err != nil { panic(err) } req.Header.Set("Authorization", "Bearer " + key) client := &http.Client{Timeout: 60 * time.Second} res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() data, err := io.ReadAll(res.Body) if err != nil { panic(err) } if res.StatusCode >= 300 { panic(fmt.Sprintf("HTTP %d: %s", res.StatusCode, data)) } fmt.Println(res.StatusCode, string(data))}// cargo add reqwest@0.13 --features blocking// Save in src/main.rs, then: cargo runuse std::{env, error::Error, time::Duration};
fn main() -> Result<(), Box<dyn Error>> { let client = reqwest::blocking::Client::builder() .timeout(Duration::from_secs(60)).build()?; let response = client.request(reqwest::Method::DELETE, "https://www.chaozapi.com/api/v1/assets/ASSET_ID/versions/VERSION_ID") .bearer_auth(env::var("GLACIER_API_KEY")?) .send()?; let status = response.status(); let text = response.text()?; if !status.is_success() { return Err(format!("HTTP {status}: {text}").into()); } println!("{status} {text}"); Ok(())}// Java 17+; save as Example.java, then: java Example.javaimport java.net.URI;import java.net.http.*;import java.time.Duration;import java.util.Objects;
class Example { public static void main(String[] args) throws Exception { var key = Objects.requireNonNull(System.getenv("GLACIER_API_KEY")); var client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build(); var request = HttpRequest.newBuilder(URI.create("https://www.chaozapi.com/api/v1/assets/ASSET_ID/versions/VERSION_ID")) .timeout(Duration.ofSeconds(60)) .header("Authorization", "Bearer " + key) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() >= 300) throw new IllegalStateException("HTTP " + response.statusCode() + ": " + response.body()); System.out.println(response.statusCode() + " " + response.body()); }}// .NET 8+; dotnet new console; replace Program.cs; dotnet runusing System;using System.Net.Http;using System.Net.Http.Headers;using System.Text;
var key = Environment.GetEnvironmentVariable("GLACIER_API_KEY") ?? throw new InvalidOperationException("Set GLACIER_API_KEY");using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };using var request = new HttpRequestMessage(new HttpMethod("DELETE"), "https://www.chaozapi.com/api/v1/assets/ASSET_ID/versions/VERSION_ID");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);using var response = await client.SendAsync(request);var text = await response.Content.ReadAsStringAsync();if (!response.IsSuccessStatusCode) throw new HttpRequestException($"HTTP {(int)response.StatusCode}: {text}");Console.WriteLine($"{(int)response.StatusCode} {text}");响应字段 · 204
成功后无响应体。不要解析为空 JSON。
删除素材
“删除素材”章节删除自己的素材并取消相关任务。请在确认不再需要原件及其版本时调用,公共示范素材不可删除。成功返回 204,没有响应正文。
/api/v1/assets/{assetId}路径、查询与请求头
| 参数 | 位置 | 类型与约束 |
|---|---|---|
assetId必填 | path | string素材 ID |
调用示例
curl --include --fail-with-body --silent --show-error --max-time 60 \ --request DELETE 'https://www.chaozapi.com/api/v1/assets/ASSET_ID' \ --header "Authorization: Bearer $GLACIER_API_KEY"// Node.js 22+; save as example.mjs, then: node example.mjsconst key = process.env.GLACIER_API_KEY;if (!key) throw new Error('Set GLACIER_API_KEY');const response = await fetch('https://www.chaozapi.com/api/v1/assets/ASSET_ID', { method: 'DELETE', headers: { Authorization: `Bearer ${key}`, }, signal: AbortSignal.timeout(60_000),});const text = await response.text();if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);console.log(response.status, text);# Python 3.10+; standard library; python example.pyimport osimport urllib.requestimport urllib.error
headers = {"Authorization": "Bearer " + os.environ["GLACIER_API_KEY"]}request = urllib.request.Request( "https://www.chaozapi.com/api/v1/assets/ASSET_ID", method="DELETE", headers=headers,)try: with urllib.request.urlopen(request, timeout=60) as response: print(response.status, response.read().decode("utf-8"))except urllib.error.HTTPError as error: raise RuntimeError(f"HTTP {error.code}: {error.read().decode('utf-8')}") from error// Go 1.22+; go run example.gopackage main
import ( "fmt" "io" "net/http" "os" "time")
func main() { key := os.Getenv("GLACIER_API_KEY") if key == "" { panic("Set GLACIER_API_KEY") } req, err := http.NewRequest("DELETE", "https://www.chaozapi.com/api/v1/assets/ASSET_ID", nil) if err != nil { panic(err) } req.Header.Set("Authorization", "Bearer " + key) client := &http.Client{Timeout: 60 * time.Second} res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() data, err := io.ReadAll(res.Body) if err != nil { panic(err) } if res.StatusCode >= 300 { panic(fmt.Sprintf("HTTP %d: %s", res.StatusCode, data)) } fmt.Println(res.StatusCode, string(data))}// cargo add reqwest@0.13 --features blocking// Save in src/main.rs, then: cargo runuse std::{env, error::Error, time::Duration};
fn main() -> Result<(), Box<dyn Error>> { let client = reqwest::blocking::Client::builder() .timeout(Duration::from_secs(60)).build()?; let response = client.request(reqwest::Method::DELETE, "https://www.chaozapi.com/api/v1/assets/ASSET_ID") .bearer_auth(env::var("GLACIER_API_KEY")?) .send()?; let status = response.status(); let text = response.text()?; if !status.is_success() { return Err(format!("HTTP {status}: {text}").into()); } println!("{status} {text}"); Ok(())}// Java 17+; save as Example.java, then: java Example.javaimport java.net.URI;import java.net.http.*;import java.time.Duration;import java.util.Objects;
class Example { public static void main(String[] args) throws Exception { var key = Objects.requireNonNull(System.getenv("GLACIER_API_KEY")); var client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build(); var request = HttpRequest.newBuilder(URI.create("https://www.chaozapi.com/api/v1/assets/ASSET_ID")) .timeout(Duration.ofSeconds(60)) .header("Authorization", "Bearer " + key) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() >= 300) throw new IllegalStateException("HTTP " + response.statusCode() + ": " + response.body()); System.out.println(response.statusCode() + " " + response.body()); }}// .NET 8+; dotnet new console; replace Program.cs; dotnet runusing System;using System.Net.Http;using System.Net.Http.Headers;using System.Text;
var key = Environment.GetEnvironmentVariable("GLACIER_API_KEY") ?? throw new InvalidOperationException("Set GLACIER_API_KEY");using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };using var request = new HttpRequestMessage(new HttpMethod("DELETE"), "https://www.chaozapi.com/api/v1/assets/ASSET_ID");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);using var response = await client.SendAsync(request);var text = await response.Content.ReadAsStringAsync();if (!response.IsSuccessStatusCode) throw new HttpRequestException($"HTTP {(int)response.StatusCode}: {text}");Console.WriteLine($"{(int)response.StatusCode} {text}");响应字段 · 204
成功后无响应体。不要解析为空 JSON。