티스토리 뷰

카테고리 없음

CloudFlare 이미지 업로드하기 (5달러, nodejs)

YG - 96년생 , 강아지 있음, 개발자 희망 2023. 12. 30. 10:21

시작하기 

클라우드 이미지 가격 정책

 

주소 

https://dash.cloudflare.com/

 

저의 경우 가장 저렴한 5달러로 진행했습니다

 

 

 

리사이징은 무료이고 20여 가지의 사이즈로 변경하여 조회할 수 있다고 합니다.

 

저장 시 저장소는 10만 이미지 당 5달러입니다. 

 

조회 시 10만 이미지 당 1달러입니다.

 

 


 

이미지 업로드 API docs 읽기

 

아래의 3가지 문서를 참고했습니다.

 

 

Make your first API request · Cloudflare Image Optimization docs

To make your first request to the Images API, you must obtain these pieces of information:

developers.cloudflare.com

 

 

Direct Creator Upload · Cloudflare Image Optimization docs

The Direct Creator Upload feature in Cloudflare Images lets your users upload images with a one-time upload URL. By using Direct Creator Upload, you …

developers.cloudflare.com

 

 

Cloudflare API Documentation

 

developers.cloudflare.com

 

먼저 프로필의 API Tokens로 들어와 토큰을 생성해야 합니다

 

 

Create Token을 누른 뒤 Create Custom Token을 눌러줍니다.

 

토큰의 사용처를 Cloudflare Images로 설정하고 Edit으로 바꾼 뒤 토큰을 생성해 줍니다

 

생성한 뒤. env 혹은 노션 등에 기록을 해줍니다.

 

 

그리고 이미지 요금을 결제했다면 다음과 같은 정보를 얻을 수 있습니다

 

그중에 Account ID를 저장해 줍니다.

 

저의 경우. env에 다음과 같이 저장했습니다.

 

NEXT_PUBLIC_ENV_CLOUDFLARE_IMAGE_API_KEY="ㅁㄴㅇㅁㄴㅇ"
NEXT_PUBLIC_ENV_CLOUDFLARE_ACCOUNT_ID="ㅁㄴㅇㅁㄴㅇ"

 

 

 

 


Cloudflare에 업로드하기

클라우드플레어에 이미지를 업로드할 url을 요청하면 1회 업로드할 수 있는 url을 반환합니다.

그리고 url을 통해 body에 파일이 들은 formData를 보내면 업로드된 이미지의 id를 반환합니다. 

 

한번 사용되면 다시 사용할 수 없고, 이미지 업로드 url의 유효 시간은 기본 30분입니다.

 

이 id를 데이터 베이스에 저장해 주면 됩니다.

 

interface CfUploadEndPointApiResult {
  result: {
    id: string;
    uploadURL: string;
  };
  success: boolean;
  errors: {
    code: number;
    message: string;
  }[];
  messages: {
    code: number;
    message: string;
  }[];
}

interface CfUploadApiResult {
  result: {
    id: string;
    metadata: {
      key: string;
    };
    uploaded: string;
    requireSignedURLs: boolean;
    variants: string[];
    draft: boolean;
  };
  success: boolean;
  errors: {
    code: number;
    message: string;
  }[];
  messages: {
    code: number;
    message: string;
  }[];
}

/**
 * cloudflare
 * 클라우드 플레어에 이미지를 업로드하는 함수
 */
export const cfImageUpload = async (file: File) => {
  const {
    result: { uploadURL },
  }: CfUploadEndPointApiResult = await (
    await fetch(
      `https://api.cloudflare.com/client/v4/accounts/${process.env.NEXT_PUBLIC_ENV_CLOUDFLARE_ACCOUNT_ID}/images/v2/direct_upload`,
      {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${process.env.NEXT_PUBLIC_ENV_CLOUDFLARE_IMAGE_API_KEY}`,
        },
      }
    )
  ).json();

  const form = new FormData();
  form.append('file', file);

  const {
    result: { id },
  }: CfUploadApiResult = await (
    await fetch(uploadURL, {
      method: 'POST',
      body: form,
    })
  ).json();

  return id;
};

 

 


DB에서 id를 가져와 사용하기

 

아래와 같이 계정 해쉬값/ 이미지 아이디 / 어떤 종류의 사이즈를 가져올 것인지를 설정해 주면 됩니다

 

계정 해쉬값은 클라우드플레어 이미지 탭에 가보면 확인할 수 있습니다

 

https://imagedelivery.net/<ACCOUNT_HASH>/<IMAGE_ID>/<VARIANT_NAME>

// 예시

https://imagedelivery.net/ZWd9g1K7eljCn_KDTu_MWA/083eb7b2-5392-4565-b69e-aff66acddd00/public

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함