在浏览器环境中对github仓库进行增删改查
·22 字·1 分钟阅读
github
基本配置
const owner = "ConsoleLZ"; // 仓库所有者
const repo = "githubAPI"; // 仓库名称
const accessToken = "???"; // GitHub 个人访问令牌
const branch = 'main' // 仓库分支
获取文件sha值的函数
// 获取文件的sha值
async function getFileSha() {
if (!fileName.value) {
return
}
const existingFileResponse = await fetch(
`https://api.github.com/repos/${owner}/${repo}/contents/${fileName.value}`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
if (existingFileResponse.ok) {
const existingFileData = await existingFileResponse.json();
return existingFileData.sha;
} else {
console.log('仓库文件不存在')
return
}
}
查
// 查询所有文件
async function findFileList() {
const fileList = await fetch(
`https://api.github.com/repos/${owner}/${repo}/contents/`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
).then(res=>res.json());
console.log(fileList)
}
增或改
// 新增或者更新文件
async function handleUploadFile() {
const file = fileInput.files[0];
if (!file || !fileName.value) {
alert("文件为空或者输入文件路径为空");
return;
}
const commitMessage = "githubAPI"; // 提交信息
// 获取文件的当前 SHA 值
let sha = await getFileSha();
// 将文件内容转换为 Base64 编码
const reader = new FileReader();
reader.onload = async function () {
const base64Content = btoa(
new Uint8Array(reader.result).reduce(
(data, byte) => data + String.fromCharCode(byte),
""
)
);
// 创建或更新文件
const fileData = {
message: commitMessage,
content: base64Content,
sha,
branch
};
const uploadResponse = await fetch(
`https://api.github.com/repos/${owner}/${repo}/contents/${fileName.value}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify(fileData),
}
);
if (uploadResponse.ok) {
alert('文件上传成功')
} else {
alert('文件上传失败')
}
};
reader.readAsArrayBuffer(file);
}
删
// 删除文件
async function handleDeleteFile() {
const sha = await getFileSha()
const message = '删除文件'
if (sha) {
const deleteResponse = await fetch(
`https://api.github.com/repos/${owner}/${repo}/contents/${fileName.value}`,
{
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
message,
sha,
branch
})
}
);
if (!deleteResponse.ok) {
throw new Error(`Failed to delete file: ${response.statusText}`);
}
alert('文件删除成功')
} else {
alert('要删除的文件不存在')
}
}
全部代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Upload File to GitHub</title>
</head>
<body>
<input type="text" id="fileName" placeholder="请选择文件路径">
<input type="file" id="fileInput" />
<button onclick="handleUploadFile()">Upload File</button>
<button style="background-color: brown;" onclick="handleDeleteFile()">删除</button>
<script>
const fileInput = document.getElementById("fileInput");
const fileName = document.getElementById("fileName");
const owner = "ConsoleLZ"; // 仓库所有者
const repo = "githubAPI"; // 仓库名称
const accessToken = "???"; // GitHub 个人访问令牌
const branch = 'main' // 仓库分支
// 新增或者更新文件
async function handleUploadFile() {
const file = fileInput.files[0];
if (!file || !fileName.value) {
alert("文件为空或者输入文件路径为空");
return;
}
const commitMessage = "githubAPI"; // 提交信息
// 获取文件的当前 SHA 值
let sha = await getFileSha();
// 将文件内容转换为 Base64 编码
const reader = new FileReader();
reader.onload = async function () {
const base64Content = btoa(
new Uint8Array(reader.result).reduce(
(data, byte) => data + String.fromCharCode(byte),
""
)
);
// 创建或更新文件
const fileData = {
message: commitMessage,
content: base64Content,
sha,
branch
};
const uploadResponse = await fetch(
`https://api.github.com/repos/${owner}/${repo}/contents/${fileName.value}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify(fileData),
}
);
if (uploadResponse.ok) {
alert('文件上传成功')
} else {
alert('文件上传失败')
}
};
reader.readAsArrayBuffer(file);
}
// 删除文件
async function handleDeleteFile() {
const sha = await getFileSha()
const message = '删除文件'
if (sha) {
const deleteResponse = await fetch(
`https://api.github.com/repos/${owner}/${repo}/contents/${fileName.value}`,
{
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
message,
sha,
branch
})
}
);
if (!deleteResponse.ok) {
throw new Error(`Failed to delete file: ${response.statusText}`);
}
alert('文件删除成功')
} else {
alert('要删除的文件不存在')
}
}
// 查询所有文件
async function findFileList() {
const fileList = await fetch(
`https://api.github.com/repos/${owner}/${repo}/contents/`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
).then(res=>res.json());
console.log(fileList)
}
findFileList()
// 获取文件的sha值
async function getFileSha() {
if (!fileName.value) {
return
}
const existingFileResponse = await fetch(
`https://api.github.com/repos/${owner}/${repo}/contents/${fileName.value}`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
if (existingFileResponse.ok) {
const existingFileData = await existingFileResponse.json();
return existingFileData.sha;
} else {
console.log('仓库文件不存在')
return
}
}
</script>
</body>
</html>