如何通過 Gitee API 上傳文件到指定倉庫

首先,進(jìn)入Gitee官方API文檔:https://gitee.com/api/v5/swagger#/postV5ReposOwnerRepoContentsPath,找到倉庫 --> 新建文件接口

該接口使用的是 POST 方法,接受 access_token,owner,repo,path,contentmessage,branch 等必要參數(shù)信息

請求成功后的返回結(jié)果數(shù)據(jù)結(jié)構(gòu)如下

我們模擬請求測試通過后,來實(shí)現(xiàn)一個 Web 版 Gitee 上傳圖片的工具,我們需要在頁面中添加一個上傳文件的組件和參數(shù)配置的頁面。根據(jù)以上模擬的結(jié)果,除了需要新建一個倉庫,取得它的倉庫名稱、私人令牌、分支名外,其他是需要我們使用程序生成的

我們使用 axios 封裝一個公共的請求方法 fetch

async function giteeUpload(content, filename) {
  const { username, repo, branch, accessToken } = getConfig();
  const dir = getDir();
  const dateFilename = getDateFilename(filename);
  const url = `https://gitee.com/api/v5/repos/${username}/${repo}/contents/${dir}/${dateFilename}`;
  const res = await fetch({
    url,
    method: "POST",
    data: {
      content,
      branch,
      access_token: accessToken,
      message: `Upload by ${window.location.href}`,
    },
  });
  return encodeURI(res.content.download_url);
}

我們需要在上傳組件獲取到文件,對文件內(nèi)容進(jìn)行 Base64 編碼

export const toBase64 = (file) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result.split(",").pop());
    reader.onerror = (error) => reject(error);
  });
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容