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

該接口使用的是 POST 方法,接受 access_token,owner,repo,path,content,message,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);
});