업로드 작동 방식
업로드는 두 단계 흐름이며, SDK는 첫 번째 단계를 도와줍니다:- 파일 레코드를 생성합니다.
files.create는 새 파일의id와 함께 미리 서명된upload_url및 함께 보낼upload_headers를 반환합니다. - 바이트를 직접 전송합니다. 해당 헤더와 함께 파일 내용을
upload_url로PUT하세요. SDK는 바이트를 대신 전송하지 않습니다.
upload_status가 ready가 됩니다. files.retrieve로 ready가 될 때까지 폴링한 다음, id를 리소스에 첨부하고 최종 url을 읽으세요.
바이트가 서버를 거치지 않도록 브라우저에서 바로 업로드하거나 큰 파일을 여러 부분으로 나누어 보내려면 파일 직접 업로드를 참고하세요.
SDK 초기화
import { WhopClient } from "@whop/sdk";
const client = new WhopClient({
token: process.env.WHOP_API_KEY,
});
import os
from whop_sdk import Whop
client = Whop(
token=os.environ["WHOP_API_KEY"],
)
require "whop_sdk"
client = Whop_sdk::Client.new(
token: ENV.fetch("WHOP_API_KEY"),
)
import (
"context"
"os"
whopsdk "github.com/whopio/whopsdk-go/v2"
whopclient "github.com/whopio/whopsdk-go/v2/client"
"github.com/whopio/whopsdk-go/v2/option"
)
client := whopclient.NewWhop(
option.WithToken(os.Getenv("WHOP_API_KEY")),
)
use whop_sdk::prelude::*;
let config = ClientConfig {
token: Some(std::env::var("WHOP_API_KEY").expect("WHOP_API_KEY is not set")),
..Default::default()
};
let client = Whop::new(config).expect("Failed to build client");
파일 업로드
레코드를 생성한 다음, 반환된 미리 서명된 URL로 바이트를PUT하세요.
import { readFile } from "node:fs/promises";
// 1. Create the file record and get a presigned upload URL
const file = await client.files.create({ filename: "photo.jpg" });
// 2. Send the bytes to storage yourself
const bytes = await readFile("./photo.jpg");
await fetch(file.upload_url!, {
method: "PUT",
headers: file.upload_headers as Record<string, string>,
body: bytes,
});
console.log(file.id); // file_xxxxxxxxxxxxx — attach it once it's ready
import requests
# 1. Create the file record and get a presigned upload URL
file = client.files.create(filename="photo.jpg")
# 2. Send the bytes to storage yourself
with open("./photo.jpg", "rb") as contents:
requests.put(
file.upload_url,
headers=file.upload_headers or {},
data=contents,
)
print(file.id) # file_xxxxxxxxxxxxx — attach it once it's ready
require "net/http"
# 1. Create the file record and get a presigned upload URL
file = client.files.create(filename: "photo.jpg")
# 2. Send the bytes to storage yourself
uri = URI(file.upload_url)
request = Net::HTTP::Put.new(uri)
(file.upload_headers || {}).each { |key, value| request[key] = value }
request.body = File.binread("./photo.jpg")
Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(request) }
puts file.id # file_xxxxxxxxxxxxx — attach it once it's ready
import (
"bytes"
"fmt"
"net/http"
"os"
)
// 1. Create the file record and get a presigned upload URL
file, err := client.Files.Create(context.TODO(), &whopsdk.CreateFilesRequest{
Filename: "photo.jpg",
})
if err != nil {
return err
}
// 2. Send the bytes to storage yourself
data, err := os.ReadFile("./photo.jpg")
if err != nil {
return err
}
request, err := http.NewRequest(http.MethodPut, *file.UploadURL, bytes.NewReader(data))
if err != nil {
return err
}
for key, value := range file.UploadHeaders {
request.Header.Set(key, fmt.Sprint(value))
}
if _, err := http.DefaultClient.Do(request); err != nil {
return err
}
fmt.Println(file.ID) // file_xxxxxxxxxxxxx — attach it once it's ready
// 1. Create the file record and get a presigned upload URL
let file = client
.files
.create(
&CreateFilesRequest {
filename: "photo.jpg".to_string(),
..Default::default()
},
None,
)
.await?;
// 2. Send the bytes to storage yourself
let contents = std::fs::read("./photo.jpg")?;
let mut request = reqwest::Client::new()
.put(file.upload_url.as_deref().unwrap())
.body(contents);
if let Some(headers) = &file.upload_headers {
for (key, value) in headers {
if let Some(value) = value.as_str() {
request = request.header(key, value);
}
}
}
request.send().await?;
println!("{}", file.id); // file_xxxxxxxxxxxxx — attach it once it's ready
공개 및 비공개 파일
업로드하는 모든 파일에는 접근을 제어하는 공개 범위가 있습니다. 공개 범위는 업로드 시점에 선택하며 나중에 변경할 수 없습니다.| 공개 범위 | URL 유형 | 접근 가능 대상 | 용도 |
|---|---|---|---|
private (기본값) | 만료되는 서명된 URL | API를 통한 앱만 | 메시지 첨부 파일, 사용자 업로드 문서, 민감한 콘텐츠, AI 생성 파일 |
public | 영구적인 서명되지 않은 콘텐츠 전송 네트워크 URL | 링크가 있는 누구나 | 상품 이미지, 썸네일, 브랜딩, 마케팅 자산 |
업로드하기 전에 공개 범위를 설정하세요. 공개 파일은 Whop의 CDN에 캐시되며 URL이 있는 누구나 접근할 수 있습니다 — 접근을 취소할 방법이 없습니다. 콘텐츠가 사용자별이거나 민감한 경우 기본값인
private를 유지하세요.공개 파일 업로드
파일을 생성할 때public 공개 범위를 전달한 다음, 같은 방식으로 바이트를 업로드하세요:
const file = await client.files.create({
filename: "product-cover.jpg",
visibility: "public",
});
// PUT the bytes to file.upload_url, then file.url is a permanent CDN URL
file = client.files.create(
filename="product-cover.jpg",
visibility="public",
)
# PUT the bytes to file.upload_url, then file.url is a permanent CDN URL
file = client.files.create(
filename: "product-cover.jpg",
visibility: "public",
)
# PUT the bytes to file.upload_url, then file.url is a permanent CDN URL
file, err := client.Files.Create(context.TODO(), &whopsdk.CreateFilesRequest{
Filename: "product-cover.jpg",
Visibility: whopsdk.CreateFilesRequestVisibilityPublic.Ptr(),
})
// PUT the bytes to file.UploadURL, then file.URL is a permanent CDN URL
let file = client
.files
.create(
&CreateFilesRequest {
filename: "product-cover.jpg".to_string(),
visibility: Some(CreateFilesRequestVisibility::Public),
..Default::default()
},
None,
)
.await?;
// PUT the bytes to file.upload_url, then file.url is a permanent CDN URL
visibility는 주로 첨부하지 않고 직접 링크하는 파일에 중요합니다.
업로드 완료 확인
바이트가 도착한 후 파일은 비동기적으로 처리됩니다.upload_status가 pending 및 processing을 벗어날 때까지 파일을 조회하세요. ready가 되면 최종 url을 읽으세요. failed가 되면 중단하고 오류를 표시하세요.
let uploaded = await client.files.retrieve({ id: file.id });
while (uploaded.upload_status === "pending" || uploaded.upload_status === "processing") {
await new Promise((resolve) => setTimeout(resolve, 1000));
uploaded = await client.files.retrieve({ id: file.id });
}
if (uploaded.upload_status !== "ready") {
throw new Error(`Upload failed: ${uploaded.upload_status}`);
}
console.log(uploaded.url);
import time
uploaded = client.files.retrieve(file.id)
while uploaded.upload_status in ("pending", "processing"):
time.sleep(1)
uploaded = client.files.retrieve(file.id)
if uploaded.upload_status != "ready":
raise RuntimeError(f"Upload failed: {uploaded.upload_status}")
print(uploaded.url)
uploaded = client.files.retrieve(id: file.id)
while %w[pending processing].include?(uploaded.upload_status)
sleep 1
uploaded = client.files.retrieve(id: file.id)
end
raise "Upload failed: #{uploaded.upload_status}" unless uploaded.upload_status == "ready"
puts uploaded.url
import "time"
uploaded, err := client.Files.Retrieve(context.TODO(), &whopsdk.RetrieveFilesRequest{ID: file.ID})
if err != nil {
return err
}
for uploaded.UploadStatus == whopsdk.FileUploadStatusPending ||
uploaded.UploadStatus == whopsdk.FileUploadStatusProcessing {
time.Sleep(time.Second)
uploaded, err = client.Files.Retrieve(context.TODO(), &whopsdk.RetrieveFilesRequest{ID: file.ID})
if err != nil {
return err
}
}
if uploaded.UploadStatus != whopsdk.FileUploadStatusReady {
return fmt.Errorf("upload failed: %s", uploaded.UploadStatus)
}
fmt.Println(*uploaded.URL)
let mut uploaded = client.files.retrieve(&file.id, None).await?;
while matches!(
uploaded.upload_status,
FileUploadStatus::Pending | FileUploadStatus::Processing
) {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
uploaded = client.files.retrieve(&file.id, None).await?;
}
if !matches!(uploaded.upload_status, FileUploadStatus::Ready) {
panic!("upload failed: {}", uploaded.upload_status);
}
println!("{}", uploaded.url.unwrap());
비공개 파일 접근
비공개 파일 URL은 만료됩니다. 새 URL을 받으려면 ID로 파일을 다시 조회하세요:const file = await client.files.retrieve({ id: "file_xxxxxxxxxxxxx" });
console.log(file.url); // fresh signed URL
file = client.files.retrieve("file_xxxxxxxxxxxxx")
print(file.url) # fresh signed URL
file = client.files.retrieve(id: "file_xxxxxxxxxxxxx")
puts file.url # fresh signed URL
file, err := client.Files.Retrieve(context.TODO(), &whopsdk.RetrieveFilesRequest{
ID: "file_xxxxxxxxxxxxx",
})
fmt.Println(*file.URL) // fresh signed URL
let file = client
.files
.retrieve(&"file_xxxxxxxxxxxxx".to_string(), None)
.await?;
println!("{}", file.url.unwrap()); // fresh signed URL
업로드된 파일 사용
파일이ready가 되면 파일 첨부를 허용하는 모든 API 호출에 해당 id를 전달하세요:
await client.courses.update({
id: "course_xxxxxxxxxxxxx",
thumbnail: { id: file.id },
});
client.courses.update(
"course_xxxxxxxxxxxxx",
thumbnail={"id": file.id},
)
client.courses.update(
id: "course_xxxxxxxxxxxxx",
thumbnail: { id: file.id },
)
client.Courses.Update(context.TODO(), &whopsdk.UpdateCoursesRequest{
ID: "course_xxxxxxxxxxxxx",
Thumbnail: &whopsdk.UpdateCoursesRequestThumbnail{ID: file.ID},
})
client
.courses
.update(
&"course_xxxxxxxxxxxxx".to_string(),
&UpdateCoursesRequest {
thumbnail: Some(UpdateCoursesRequestThumbnail { id: file.id }),
..Default::default()
},
None,
)
.await?;
파일 속성
| 속성 | 설명 |
|---|---|
id | 고유 식별자(예: file_xxxxxxxxxxxxx) |
filename | 원본 파일 이름 |
content_type | 파일 이름의 확장자로 추론한 미디어 유형(예: image/jpeg) |
size | 바이트 단위의 파일 크기. 업로드가 완료될 때까지 null |
url | 파일을 다운로드할 위치: 공개 파일은 영구적인 콘텐츠 전송 네트워크 URL, 비공개 파일은 만료되는 서명된 URL. 업로드가 완료될 때까지 null |
upload_status | 상태: pending, processing, ready 또는 failed |
visibility | public 또는 private |
upload_url | 바이트를 PUT할 미리 서명된 URL. create 응답에만 존재 |
upload_headers | 업로드 PUT과 함께 보낼 헤더. create 응답에만 존재 |

