当前位置:网站首页 > 更多 > 站长帮 > 正文

[WEB] 图床,通过Python调用api上传图片到Gitlab

作者:CC下载站 日期:2022-11-07 00:00:00 浏览:72 分类:站长帮

用过一段时间的PicGo,但是感觉太重了,为了一个上传图片去装一个软件有点太麻烦。
然后目前个人感觉也就Gitlab速度还可以一点,于是昨天翻了官方文档踩了很多坑,总算搞好了。
现将关键代码放到这里。

    file_path = datetime.datetime.now().strftime('zb_users/upload/%Y/%m/')
    headers = {'PRIVATE-TOKEN': '这里放你的项目token'}
    img = file.file.read()
    ext = file.content_type.split('/')[-1]
    file_path = urllib.parse.quote(file_path + uuid.uuid4().hex + '.' + ext).replace('/', '%2f')
    url = f'https://gitlab.com/api/v4/projects/这里放你的项目ID/repository/files/{file_path}'
    response = await requests.post(url, headers=headers, json={
        'branch': 'master',
        'content': base64.b64encode(img).decode('utf-8'),
        'author_email': [email protected]',
        'author_name': 'Lan',
        'encoding': 'base64',
        'commit_message': 'www.lanol.cn'
    })
    res = await response.json()

然后花了点时间写了个小前端用来上传,支持选择,拖拽,粘贴文件进行上传。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯