当前位置:   article > 正文

Typora自定义Python脚本上传图片到Gitee_typora自定义上传

typora自定义上传

Typora自定义Python脚本上传图片到Gitee

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

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

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

1、打开并登入 Gitee,新建仓库,设置好仓库名称和路径,选择开源(重要),勾选初始化仓库,创建。

2、点击导航栏的头像,选择设置:

image-20210606033140304

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

image-20210606033253209

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

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

image-20210606033706498

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()
  • 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

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

image-20210606033751835

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/773238
推荐阅读
相关标签
  

闽ICP备14008679号