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

调用Azure DevOps Attachments-Create API上传图片附件无法渲染问题

问题原因

附件上传环节的请求格式不符合Azure DevOps接口要求:调用附件创建API时使用了requests的files参数,该参数会自动将请求封装为multipart/form-data格式,额外在二进制文件内容前后添加了表单分隔标识,导致最终存储的文件内容被污染,图片类文件自然无法正常解码渲染。

修复方案

修改附件上传部分的请求逻辑,直接将文件二进制流放入请求体即可,无需使用files参数,修复后的完整代码如下:

import os
import requests

def upload_attachment(file_path, work_item_id, organization, project, pat):
    # 第一部分:获取附件链接
    file_size = os.path.getsize(file_path)
    headers = {
        "Accept": "application/json",
        "Content-Size": str(file_size),
        "Content-Type": "application/octet-stream",
    }
    filename = os.path.basename(file_path)
    api = f"https://dev.azure.com/{organization}/{project}/_apis/wit/attachments?uploadType=Simple&fileName={filename}&api-version=6.0"
    # 直接用data参数传递二进制文件内容,不要使用files参数
    with open(file_path, 'rb') as f:
        resp = requests.post(url=api, data=f, headers=headers, auth=("", pat))    
    resp.raise_for_status()
    attachment_url = resp.json()['url']

    # 第二部分:更新工作项关联附件,原有逻辑无需修改
    api = f"https://dev.azure.com/{organization}/_apis/wit/workitems/{work_item_id}?api-version=6.0"
    payload = [
        {
            "op": "add",
            "path": "/relations/-",
            "value": {
                "rel": "AttachedFile",
                "url": attachment_url,
                "attributes": {
                    "comment": "Test",
                    "resourceSize": file_size
                }
            }
        }
    ]
    headers = { 
        'Accept':'application/json', 
        'Content-type':'application/json-patch+json'
    }
    resp = requests.patch(url=api, headers=headers, json=payload, auth=("", pat))
    resp.raise_for_status()

额外调整说明

  • 附件创建API建议统一使用6.0版本,避免跨版本兼容问题
  • 新增了resp.raise_for_status()方便快速捕获接口请求报错
  • 改用with语句打开文件,避免文件句柄泄漏
  • 移除了不必要的dataType请求头,该参数是jQuery的专有配置,requests库无需传入
  • 请确认你的PAT具备工作项读写、附件上传的权限,避免权限不足导致的隐性问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 05:06:04