我用的方法
发帖
"https://dev.azure.com/{organization}/{project}/_apis/wit/attachments?uploadType=Simple&fileName={filename}&api-version=5.0"
标题
headers = {
"Accept": "application/json",
"Content-Size": str(os.path.getsize(file_path)),
"Content-Type": "application/octet-stream",
}
我得到了成功的响应和图像的链接,但图像“损坏”,白色方块而不是原始图像
我们可以先调用这个API上传包含二进制文件内容的附件图像,然后发送这个请求将上传的文件添加为工作项的附件。
这是供您参考的示例 Python 脚本,它在我这边工作。
import base64
import json
import requests
# Define your Azure DevOps organization, project, and personal access token
organization = "YourADOOrgName"
project = "TheProjectName"
personal_access_token = 'XXXXXX'
# Encode the personal access token in base64
base64_pat = base64.b64encode(f':{personal_access_token}'.encode('utf-8')).decode('utf-8')
# Define the path to your image file
image_file_path = "C:/Users/Alvin/Desktop/testImage.png"
# Read the binary contents of the image file
with open(image_file_path, "rb") as image_file:
image_file_bytes = image_file.read()
# Define the URL for uploading the attachment
upload_url = f"https://dev.azure.com/{organization}/_apis/wit/attachments?fileName=testImage.png&uploadType=Simple&api-version=7.1-preview.3"
headers = {
"Authorization": f"Basic {base64_pat}",
"Content-Type": "application/octet-stream"
}
# Make the API request to upload the binary file
response = requests.post(upload_url, headers=headers, data=image_file_bytes)
upload_response = response.json()
# Get the attachment URL from the upload response
attachment_url = upload_response['url']
# Define the URL for updating the work item
work_item_id = 2308
wit_url = f"https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/{work_item_id}?api-version=7.1-preview.3"
# Define the body for the work item update request
attachment_body = [
{
"op": "add",
"path": "/relations/-",
"value": {
"rel": "AttachedFile",
"url": attachment_url,
"attributes": {
"comment": "Add a test image attachment from Python script"
}
}
}
]
# Make the API request to update the work item
headers["Content-Type"] = "application/json-patch+json"
response = requests.patch(wit_url, headers=headers, json=attachment_body)
update_response = response.json()
# Print the response of the work item update request
print(json.dumps(update_response, indent=4))