🚀

GitHub REST API で画像を repo にアップロードする

2023/01/24に公開

TypeScript/JavaScript で画像(というかファイル)を GitHub の任意のリポジトリにアップロードする方法。In Browser, fetch 使用。

const file: File = <your file object>;

// File to Base64 string
const fileToBase64 = (file: File): Promise<string> => {
  return new Promise<string>((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = (r) => {
      const base64str = (r.target?.result as string).replace(/data:.*\/.*;base64,/, '');
      resolve(base64str);
    };
    reader.onerror = (e) => reject(e);
  });
};
const content = await fileToBase64(file);

const data = JSON.stringify({
  branch: 'develop',
  message: 'upload image',
  content: `${content}`
});

const token = '<your_github_personal_access_token>';
const owner = '<repository_owner>';  // ex: amay077
const repo = '<repository_name>'; // ex: blog-poster

const url = `https://api.github.com/repos/${owner}/${repo}/contents/awesome_images/something.png`;

const p = {
  method: 'PUT',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': file.type
  },
  body: data
};

const res = await fetch(url, p);
if (res.ok) {
  const resJson = await res.json();
  console.log(`Upload succeeded.`, resJson.content.download_url);
} else {
  console.log(`Upload failed.`, res.status);
}

参考

Discussion