github file upload

본 블로그의 이미지를 github에 올려서 호스팅 하기 위한 스크립트이다.


import os
import base64
from pathlib import Path
from urllib.parse import quote

import requests

# GitHub 설정
GITHUB_TOKEN = "your token"

OWNER = "mcjoi"
REPO = "img1-repo"
BRANCH = "master"


def upload_image(file_path, github_folder):
    file_path = Path(file_path)

    if not file_path.is_file():
        raise FileNotFoundError(f"파일이 없습니다: {file_path}")

    file_name = file_path.name

    # GitHub 폴더 경로 정리
    github_folder = github_folder.replace("\\", "/").strip("/")
    repo_path = (
        f"{github_folder}/{file_name}"
        if github_folder else file_name
    )
    encoded_path = quote(repo_path, safe="/")

    # 이미지 Base64 변환
    with open(file_path, "rb") as f:
        content = base64.b64encode(f.read()).decode("utf-8")

    api_url = (
        f"https://api.github.com/repos/{OWNER}/{REPO}"
        f"/contents/{encoded_path}"
    )

    headers = {
        "Authorization": f"Bearer {GITHUB_TOKEN}",
        "Accept": "application/vnd.github+json",
        "X-GitHub-Api-Version": "2022-11-28",
    }

    data = {
        "message": f"Upload {file_name}",
        "content": content,
        "branch": BRANCH,
    }

    # 기존 파일 확인 (있으면 덮어쓰기)
    existing = requests.get(
        api_url,
        headers=headers,
        params={"ref": BRANCH},
        timeout=30
    )

    if existing.status_code == 200:
        data["sha"] = existing.json()["sha"]
    elif existing.status_code != 404:
        existing.raise_for_status()

    # GitHub 업로드
    response = requests.put(
        api_url,
        headers=headers,
        json=data,
        timeout=60
    )
    response.raise_for_status()

    # 업로드된 이미지 URL
    image_url = (
        f"https://raw.githubusercontent.com/"
        f"{OWNER}/{REPO}/refs/heads/{BRANCH}/{encoded_path}"
    )

    return image_url


if __name__ == "__main__":
    print("===== GitHub 이미지 업로드 =====")

    local_file = input("로컬 이미지 파일 경로: ").strip().strip('"')
    github_folder = input(
        "GitHub 업로드 폴더 (예: life/05859): "
    ).strip()

    try:
        url = upload_image(local_file, github_folder)
        print("\n업로드 완료!")
        print("이미지 URL:", url)
    except Exception as e:
        print("\n업로드 실패:", e)

업로드할 파일 경로를 입력한다.
파일을 저장할 repo의 경로를 입력한다.

파일명이 중복이 되는 경우, overwriting 된다.

끝.