前端知识体系
GitHub (opens new window)

GuoLiBin6

程序员永不下班
GitHub (opens new window)
  • 介绍
  • 前端基础

  • 浏览器基础

  • 软件开发

    • vscode

    • mac配置

    • github

      • 利用github API上传图片
  • 数据结构

  • 性能优化

  • Node.js

  • 收录

  • 搞事啦

  • 前端知识体系
  • 软件开发
  • github
GuoLiBin6
2024-01-08

利用github API上传图片

GitHub API (opens new window)

在探究 如何管理自己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
上次更新: 2024-01-08 20:20:24
设置alias告别繁琐命令
栈

← 设置alias告别繁琐命令 栈→

最近更新
01
蛤蟆先生去看心理医生
04-12
02
梁永安:阅读、游历和爱情
03-20
03
阿甘正传
02-07
更多文章>
Theme by Vdoing | Copyright © 2022-2024 GuoLiBin6
冀ICP备2022013865号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式