脚本上传typora图片到gitee

用 Gitee 搭建图床,上传要用到 Gitee 的开放API:https://gitee.com/api/v5/swagger#/postV5ReposOwnerRepoContentsPath

注意:Gitee 的图片预览只能预览 1M 以内的图片,超过这个大小会要求登录。用 Gitee 作为图床的话图片尽量控制图片在 1M 以内。

直接进入主题,用 Gitee 搭建属于自己的图床并通过 Typroa 自定义脚本上传图片。

1、打开并登入 Gitee,新建仓库,设置好仓库名称和路径,选择开源(重要),勾选初始化仓库,创建。
2、点击导航栏的头像,选择设置:

![在这里插入图片描述]( https://img-blog.csdnimg.cn/160ea17fbfdb4e088b64923f967375df.png?x-oss-process=image/watermark ,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA44CK6Jma5bm756eB5aG-44CL,size_20,color_FFFFFF,t_70,g_se,x_16)

3、在设置里面选择私人令牌,然后点生成新令牌:

![在这里插入图片描述]( https://img-blog.csdnimg.cn/225b8f757801486cadf7f4b5fbdc7bec.png?x-oss-process=image/watermark ,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA44CK6Jma5bm756eB5aG-44CL,size_20,color_FFFFFF,t_70,g_se,x_16)

4、输入私人令牌描述后点击提交即可,弹出私人令牌生成提示,复制生成的私人令牌(重要)。

5、打开 Typora,找到”文件–>偏好设置–>图像“,设定如下:

![在这里插入图片描述]( https://img-blog.csdnimg.cn/9d835ec5c69c47a7a5204058be80725d.png?x-oss-process=image/watermark ,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA44CK6Jma5bm756eB5aG-44CL,size_20,color_FFFFFF,t_70,g_se,x_16)

6、新建脚本文件(这里用python为例),文件位置和名称随便,脚本内容如下

import sys
import base64
import hashlib
import datetime
import requests
import urllib.parse
import os


def main():
    token = '私人令牌'
    owner = '个人空间地址名(不带https链接)'
    repo = '仓库地址名(不带https链接)'
    message = '仓库提交信息'
    
    mdname = ''

    param = [urllib.parse.unquote(par, 'utf8') for par in sys.argv]  # 把url编码转换成中文
    param.__delitem__(0)  # 第一个参数是脚本文件本身
    if len(param) > 0:
        if not os.path.exists(param[0]):  # 通过判断第一个参数是不是文件来判断是否加了参数 ${filename}
            mdname = param[0]  # 若不是文件则取出作为当前md文件名
            param.__delitem__(0)
        for i in range(0, len(param)):
            with open(param[i], "rb") as f:
                content = base64.b64encode(f.read())
                data = {'access_token': token, 'message': message, 'content': content}

                filename = hashlib.md5(content).hexdigest() + param[i][param[i].rfind('.'):]
                path = 'typora/' + (mdname if mdname != '' else str(datetime.date.today())) + '/' + filename
                res = requests.post('https://gitee.com/api/v5/repos/' + owner + '/' + repo + '/contents/' + path, data)
                if res.status_code == 201 or res.text == '{"message":"文件名已存在"}':
                    print('https://gitee.com/' + owner + '/' + repo + '/raw/master/' + path)
                else:
                    print('Error uploading Gitee, please check')


if __name__ == '__main__':
    main()

7、回到 Typroa ”偏好设置–>图像“,在命令处写上脚本文件的绝对位置(用引号引起来),点击验证图片上传选项

![在这里插入图片描述]( https://img-blog.csdnimg.cn/c50338a5defd41b59c487513a8bd6276.png?x-oss-process=image/watermark ,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA44CK6Jma5bm756eB5aG-44CL,size_20,color_FFFFFF,t_70,g_se,x_16)

打开自己建的 Gitee 仓库,可以看到新建的图片文件说明上传成功

posted @ 2022-11-24 20:48  oldSimon  阅读(172)  评论(0)    收藏  举报