接入文档
把您的网站上传、下载接到本平台:密钥只放在您的服务器,用户浏览器把文件直接传到云端,页面上只展示您的下载域名。
接入架构(浏览器直传)
文件内容不经过您的网站服务器,也不落在密钥所在机器的磁盘上;访客只看到您的站点域名或您配置的下载域名。
- 浏览器 → 您的网站(已登录)申请上传
- 您的网站用 API 密钥向本平台申请上传,拿到临时上传地址和 upload_id
- 浏览器把文件 PUT 到临时上传地址(不要带密钥,也不要把该地址展示给用户)
- 您的网站通知本平台「上传完成」:写库并返回下载地址;可选带上业务参数;需要时可异步通知您的回调地址
- 在控制台配置回调地址;上传成功后您会收到「文件已创建」通知(含下载链接和您传入的业务参数)
Browser Your app (API Key) Platform
| | |
|-----POST /my/upload-init----->| |
| |----POST /api/v1/upload/init---->|
| |<----upload_id + upload URL------|
|<---upload_id + upload URL-----| |
|-PUT file bytes (no Bearer)----|-------------------------------->|
|-----POST /my/upload-done----->| |
| |--POST /api/v1/upload/complete-->|
| |<----object_id + /dl + meta------|
| | (platform writes object meta) |
| |-----Webhook object.created----->| your callback
|<-----public /dl/{token}-------| |
| (show only this URL) | |
安全与展示约定
- API 密钥只放在您的服务器,不要写进网页脚本、App 安装包或公开仓库。
- 申请上传时返回的临时地址只用于上传;不要显示在页面上、不要当下载链接发给访客。
- 给访客看的地址只能是本平台的下载短链、您的自定义域名,或您自己的反代域名。
- 面向用户的文案不要出现底层云厂商名称;对用户只说「上传到云端 / 文件已保存」。
- 申请上传时可附带业务参数(订单号、用户 ID 等,最多 16 项);完成上传的响应和回调会原样带回,方便您写业务库。
协议步骤
1. 发起上传(服务端)
提交存储桶、文件名、类型、大小,以及可选的业务参数;换取 upload_id 与临时上传地址。
POST /api/v1/upload/init
Authorization: Bearer <api_key>
Content-Type: application/json
{
"bucket": "assets",
"filename": "photo.jpg",
"content_type": "image/jpeg",
"size": 102400,
"metadata": { "order_id": "A1001", "user_id": "42" }
}
→ {
"success": true,
"data": {
"upload_id": "...",
"presigned_url": "https://…", // temporary upload URL — PUT only, never show visitors
"headers": { "Content-Type": "image/jpeg", "Content-Length": "102400" },
"object_key": "t1/assets/…",
"expires_in": 3600,
"mode": "direct",
"metadata": { "order_id": "A1001", "user_id": "42" }
}
}
3. PUT 文件内容
必须带上申请上传时返回的请求头(通常含 Content-Type、Content-Length)
PUT <presigned_url> # 只发一次 PUT;不要附加 Authorization: Bearer Content-Type: <from data.headers> Content-Length: <size> Body: 原始文件内容(可流式上传)
4. 完成上传(服务端)
POST /api/v1/upload/complete
Authorization: Bearer <api_key>
Content-Type: application/json
{ "upload_id": "<upload_id>" }
→ {
"success": true,
"data": {
"object_id": 123,
"size": 102400,
"object_key": "…",
"url": "https://tuboyun.com/dl/…",
"metadata": { "order_id": "A1001", "user_id": "42" }
}
}
# 本平台核对大小后保存文件信息,返回访客可用的下载地址,并异步通知您的回调(含业务参数)
6. 业务回调通知
在控制台配置 HTTPS 回调地址。上传成功后本平台会异步 POST;请校验签名,并用业务参数关联您的订单。
POST https://your.example.com/hooks/supcloud
Content-Type: application/json
X-SupCloud-Event: object.created
X-SupCloud-Signature: sha256=…
{
"api_version": "v1",
"event": "object.created",
"created_at": 1730000000,
"tenant_id": 12,
"bucket": "assets",
"metadata": { "order_id": "A1001", "user_id": "42" },
"object": {
"id": 123,
"key": "t12/assets/…",
"size": 102400,
"mime": "image/jpeg",
"url": "https://tuboyun.com/dl/…",
"metadata": { "order_id": "A1001", "user_id": "42" }
}
}
# 验签:HMAC-SHA256(secret, timestamp+"."+raw_body);返回 2xx 即成功,失败会重试
5. 签发访客可用的下载地址
完成上传时已返回下载地址;也可稍后用文件 ID 再换短期链接。页面、邮件、分享里只放这类地址。
POST /api/v1/objects/url
Authorization: Bearer <api_key>
Content-Type: application/json
{ "id": 123 }
→ { "success": true, "data": { "url": "https://tuboyun.com/dl/<token>", "expires_in": 900 } }
# Put data.url into <img> / <a href> / emails — never the temporary upload URL.
接入样例
推荐做法:由您的网站代理「申请上传 / 完成上传」;浏览器只负责把文件传到临时地址。下面示例中的平台地址会按当前站点自动填充。
<?php
// server-side only — never expose SUPCLOUD_API_KEY to the browser
const SC_BASE = 'https://tuboyun.com';
const SC_KEY = getenv('SUPCLOUD_API_KEY');
function sc_request(string $method, string $path, ?array $body = null): array {
$ch = curl_init(SC_BASE . $path);
$headers = [
'Authorization: Bearer ' . SC_KEY,
'Content-Type: application/json',
'Accept: application/json',
];
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $body === null ? null : json_encode($body, JSON_UNESCAPED_UNICODE),
CURLOPT_TIMEOUT => 30,
]);
$raw = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$json = json_decode((string)$raw, true);
if ($code >= 400 || empty($json['success'])) {
throw new RuntimeException(($json['message'] ?? 'request failed') . " ($code)");
}
return $json['data'];
}
/** Called by your authenticated front-end: returns upload slot (hide presigned_url from HTML). */
function sc_init_upload(string $bucket, string $filename, string $contentType, int $size, array $metadata = []): array {
$body = [
'bucket' => $bucket,
'filename' => $filename,
'content_type' => $contentType,
'size' => $size,
];
if ($metadata) { $body['metadata'] = $metadata; } // echoed on Complete + Webhook
return sc_request('POST', '/api/v1/upload/init', $body);
}
function sc_complete_upload(string $uploadId): array {
return sc_request('POST', '/api/v1/upload/complete', ['upload_id' => $uploadId]);
}
/** Visitor-safe delivery URL — store object_id in your DB, mint URL when rendering. */
function sc_delivery_url(int $objectId): string {
$data = sc_request('POST', '/api/v1/objects/url', ['id' => $objectId]);
return $data['url']; // https://tuboyun.com/dl/...
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
const scBase = "https://tuboyun.com"
func scKey() string { return os.Getenv("SUPCLOUD_API_KEY") }
func scRequest(method, path string, body any) (map[string]any, error) {
var rdr io.Reader
if body != nil {
b, _ := json.Marshal(body)
rdr = bytes.NewReader(b)
}
req, err := http.NewRequest(method, scBase+path, rdr)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+scKey())
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
cli := &http.Client{Timeout: 30 * time.Second}
res, err := cli.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
var env struct {
Success bool `json:"success"`
Message string `json:"message"`
Data map[string]interface{} `json:"data"`
}
if err := json.NewDecoder(res.Body).Decode(&env); err != nil {
return nil, err
}
if res.StatusCode >= 400 || !env.Success {
return nil, fmt.Errorf("%s (%d)", env.Message, res.StatusCode)
}
return env.Data, nil
}
func scInitUpload(bucket, filename, contentType string, size int64, metadata map[string]string) (map[string]any, error) {
body := map[string]any{
"bucket": bucket, "filename": filename,
"content_type": contentType, "size": size,
}
if len(metadata) > 0 {
body["metadata"] = metadata // echoed on Complete + Webhook
}
return scRequest("POST", "/api/v1/upload/init", body)
}
func scCompleteUpload(uploadID string) (map[string]any, error) {
return scRequest("POST", "/api/v1/upload/complete", map[string]any{"upload_id": uploadID})
}
func scDeliveryURL(objectID int64) (string, error) {
data, err := scRequest("POST", "/api/v1/objects/url", map[string]any{"id": objectID})
if err != nil {
return "", err
}
return data["url"].(string), nil // visitor-safe /dl/{token}
}
// Node 18+ (native fetch). Keep SUPCLOUD_API_KEY in server env only.
const SC_BASE = 'https://tuboyun.com';
const SC_KEY = process.env.SUPCLOUD_API_KEY;
async function scRequest(method, path, body) {
const res = await fetch(SC_BASE + path, {
method,
headers: {
Authorization: `Bearer ${SC_KEY}`,
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: body == null ? undefined : JSON.stringify(body),
});
const json = await res.json();
if (!res.ok || !json.success) {
throw new Error(`${json.message || 'request failed'} (${res.status})`);
}
return json.data;
}
/** Return this JSON to the browser — do not embed the URL in HTML attributes. */
async function scInitUpload(bucket, filename, contentType, size, metadata) {
const body = { bucket, filename, content_type: contentType, size };
if (metadata) body.metadata = metadata; // echoed on Complete + Webhook
return scRequest('POST', '/api/v1/upload/init', body);
}
async function scCompleteUpload(uploadId) {
return scRequest('POST', '/api/v1/upload/complete', { upload_id: uploadId });
}
async function scDeliveryUrl(objectId) {
const data = await scRequest('POST', '/api/v1/objects/url', { id: objectId });
return data.url; // https://tuboyun.com/dl/...
}
module.exports = { scInitUpload, scCompleteUpload, scDeliveryUrl };
<!-- On YOUR site. Talk to YOUR backend only — never put the API key here. -->
<input type="file" id="file" />
<button type="button" id="btn">Upload</button>
<img id="preview" alt="" hidden />
<script src="/static/js/jquery.min.js"></script>
<script>
$('#btn').on('click', async function () {
var file = $('#file')[0].files[0];
if (!file) return;
// 1) Ask YOUR backend for an upload slot (it calls platform Init with the API key)
var slot = await $.ajax({
url: '/my/upload-init',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({
filename: file.name,
content_type: file.type || 'application/octet-stream',
size: file.size
})
});
// slot.data: { upload_id, presigned_url, headers }
// 2) Browser PUT — temporary URL is used once and discarded (not shown in the UI)
var headers = slot.data.headers || {};
var putRes = await fetch(slot.data.presigned_url, {
method: 'PUT',
headers: headers,
body: file
});
if (!putRes.ok) throw new Error('upload failed: ' + putRes.status);
// 3) YOUR backend completes + returns a visitor-safe /dl URL
var done = await $.ajax({
url: '/my/upload-complete',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({ upload_id: slot.data.upload_id })
});
// done.data.url === 'https://tuboyun.com/dl/…' (or your custom domain)
$('#preview').attr('src', done.data.url).prop('hidden', false);
});
</script>
更多接口
GET /api/v1/objects?bucket=assets— 分页列出文件,支持前缀与关键词搜索POST /api/v1/objects/url— 生成短期下载地址/dl/<token>,可直接嵌入图片或视频GET /dl/<token>— 按令牌下载文件,支持限速与用量统计POST /api/v1/objects/delete— 删除文件或移入回收站GET/POST /api/v1/buckets— 创建与列出存储桶GET/POST /api/v1/keys— 创建与吊销 API 密钥GET/POST /api/v1/webhooks— 上传完成回调(带签名校验)GET/POST /api/v1/domains— 自定义下载域名与跨域规则