Azure DevOps上传图片。

3

我正在使用Python将大量数据导入Azure Devops。我已经让所有的部分都正常工作了。我可以上传图片,但问题是当我从Devops网站下载图片时它不是一个有效的文件。我将分享我的图片上传代码。

def convertAttachmentToJsonBinary(attachmentPath):
    file = open(attachmentPath, 'rb')
    file_data = file.read()
    encoded_data = base64.b64encode(file_data)
    decoded_data = encoded_data.decode()
    data = "[" + decoded_data + "]"
    return data


def patchWorkItemWithAttachment(case_id, att_id, att_url):
    json_template = open("attachment.json", "r")
    json_data = json.load(json_template)
    json_data[0]['value']['url'] = att_url
    json_data[0]['value']['attributes']['comment'] = "Adding attachment"

    response = requests.patch(patch_workitem_url.replace("{id}", case_id), json=json_data, headers=headers)
    print(response.json())

在上传新案例时,我创建案例,添加附件,然后使用新附件更新新创建的案例。所有这些工作都已完成。我可以在线查看我的案例中的附件,但是当我下载它时,文件无效。 Image on Devops enter image description here 我尝试将数据读取为字节数组,如下所示:
def convertAttachmentToJsonBinary(attachmentPath):
    file = open(attachmentPath, 'rb')
    encoded_data = bytearray(file.read())

    data = "[" + str(encoded_data) + "]"
    return data

我遇到了同样的错误,上传图片可以正常工作,但下载图片时却无效。
1个回答

1
我再次测试后发现,成功上传附件Rest API返回的URL无法打开。因此,在上传时图片已经损坏。
请尝试使用bytearray(image_file.read())将图像转换为字节数组
请替换<>的值。
import requests
import base64
from io import BytesIO

pat = 'xxx'
authorization = str(base64.b64encode(bytes(':'+pat, 'ascii')), 'ascii')
url = 'https://dev.azure.com/<org_name>/<image_name>/_apis/wit/attachments?fileName=<filename.bmp>&api-version=6.0'

headers = {
    'Content-Type': 'application/octet-stream', 
    'Authorization': 'Basic '+authorization
}

#upload to attachment
with open("<image_path>", "rb") as image_file:
    # base64 doesn't work well
    # encoded_data = base64.b64encode(image_file.read())
    # decoded_data = encoded_data.decode()
    # data = "[" + decoded_data + "]"
    data = bytearray(image_file.read())

    r = requests.post(url, data=data, 
        headers=headers)

    print(r.text)

#connect wit with attachment
......

嘿,你是用Python脚本上传还是通过Web浏览器上传?当我通过Web界面上传任何图像类型时,可以下载图像并且正常工作。因此,脚本出了问题。 - Michael
你好 @Michael,我已经尝试重新检查了一下问题,并成功上传了图片。我将编辑答案。 - unknown
非常有趣,我会试一试! - Michael
不幸的是,我用新代码仍然得到相同的错误。 - Michael
你好 @Michael,能否打开附件 Rest API 返回的 URL?它是否正常显示图片? - unknown

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接