利用github API上传图片
在探究 如何管理自己github图库时,利用github API写了一段测试程序,可以从本地选取图片上传到github指定仓库指定目录,程序粗糙,先在此记录一下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gihub 上传图片</title>
</head>
<body>
<input type="file" id="file" accept="image/*">
<input id="name" />
</body>
<script type="module">
import { Octokit, App } from "https://esm.sh/octokit";
let file
document.getElementById('file').onchange = function loadFile(event) {
const file = event.target.files[0];
readAsDataURL(file)
}
function readAsDataURL(file){
if(typeof FileReader=='undifined') //判断浏览器是否支持filereader
{
result.innerHTML="<p>抱歉,你的浏览器不支持 FileReader</p>";
return false;
}
if(!/image\/\w+/.test(file.type)) //判断获取的是否为图片文件
{
alert("请确保文件为图像文件");
return false;
}
var reader=new FileReader();
reader.readAsDataURL(file);
reader.onload=function(e) {
const { result} = e.target
tiny(result.replace("data:image/jpeg;base64,", ""), file.name)
}
}
async function tiny (content, name) {
const octokit = new Octokit({
auth: '<you github token>'
})
await octokit.request('PUT /repos/GuoLiBin6/images/contents/tech-blog/' + name, {
owner: 'GuoLiBin6',
repo: 'images',
path: 'tech-blog',
message: 'add image',
committer: {
name: '<your name>',
email: '<your email>'
},
content,
headers: {
'X-GitHub-Api-Version': '2022-11-28'
}
})
xhr.send(file);
}
</script>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
上次更新: 2024-01-08 20:20:24