- 사용자가 1회성 업로드 URL을 통해 파일(이미지 또는 동영상)을 Cloudflare로 직접 업로드할 수 있도록 제공하는 기능
- API 키나 토큰을 클라이언트에 노출하지 않으며, 서버를 거치지 않고 클라이언트가 Cloudflare에 바로 업로드
주요 특징
- 1회성 업로드 URL 발급:
- 서버에서 Cloudflare API를 호출해 업로드 URL을 생성합니다.
- 해당 URL은 기본적으로 30분 동안 유효하며, 사용 후 재사용할 수 없음
- 클라이언트 직접 업로드:
- 클라이언트는 발급받은 URL로&body에 formdata를 담아 POST 요청해서, 파일을 Cloudflare로 직접 업로드
- 서버는 파일을 저장하거나 처리하지 않아도 되므로 리소스 소모가 줄어듦
- 업로드 url 생성만 하는 것은 무료(서버에 공간을 만들어 달라고 하는 것)
방법
- [서버] Cloudflare API를 호출해 업로드 URL을 생성
- next.js에서는 서버액션 함수에서 호출!
const { success, result } = await fetch("~",{ method: "POST", headers: { "Authorization" : `Bearer ${API_KEY}` } }) if (success) { const {id, uploadURL } = result ...
- [클라이언트] fetch를 이용해 파일을 Cloudflare로 직접 업로드
- url : 발급받은 URL로
- method : POST
- body : input의 file 객체를 담은 formdata
const formData = new FormData() formData.append("file", file) const response = await fetch(uploadURL,{ method: "POST", body: formData })
- Cloudflare 홈페이지에서 발급된 url에 1에서 생성된 id를 덧붙여 db에 저장
- formData의 photo 키의 값을 교체 (File → string)
- db create하는 액션 return
const interceptAction = async (_, formData: FormData) => { const photoUrl = `https://~~~~~/${id}` formData.set("photo", photoUrl) return createProduct(_,formData) //db create하는 액션 }
- variants를 붙여서 image 컴포넌트의 src로 쓰면 됨!
<Image src={`${product.image}/variant`} /> <Image src={`${product.image}/width=100,height=100`} />
- next.config.mjs에서 이미지 url의 hostname 을 등록해주기!
variants
응답으로 받은 url 뒤에 뭘 붙이느냐에 따라 변환된 이미지를 획득할 수 있다!
- variant 추가하기
: Images > Variants > variant name 입력 후 Add New Variant > 원하는 이미지 변환 커스터마이징(크기, blur 등)
- 그 외 transformation parameter (url에 붙이는 변환 속성들)