You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用python-gitlab推送JPG至GitLab仓库遇UnicodeDecodeError求助

解决python-gitlab推送JPG图片时的UnicodeDecodeError问题

问题根源在于GitLab API要求二进制文件内容需以Base64编码字符串传递,你直接传入原始二进制字节后,python-gitlab库会尝试用UTF-8解码这些字节,从而触发编码错误。

修改方案如下:

  1. 导入base64模块,将读取的二进制图片内容编码为Base64字符串
  2. 将编码后的字符串传入files.create的content参数

修改后的代码:

import gitlab
import base64

gl = gitlab.Gitlab(GITLAB_URL, PRIVATE_TOKEN)
project = gl.projects.get(PROJECT_ID)

with open(file_path, 'rb') as f:
  file_content = f.read()

# 将二进制内容编码为Base64字符串
encoded_content = base64.b64encode(file_content).decode('utf-8')

branch = project.branches.get('main')

project.files.create(
  {
    'file_path': f"{REPOSITORY_PATH}/{PATH_IN_REPO}",
    'branch': branch.name,
    'content': encoded_content,
    'commit_message': commit_message
  }
)

补充说明:

  • JPG属于二进制文件,无法用UTF-8编码解析,必须通过Base64转成可被API识别的文本格式
  • base64.b64encode()返回字节对象,需要用decode('utf-8')转成字符串才能符合API参数要求

内容的提问来源于stack exchange,提问作者Limone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 15:37:33