Azure Devops Upload Image
I am importing a lot of data into Azure Devops using python. I have all the pieces working. I can upload images, my issue is when I download the image from the Devops website it is not a valid file. I will share my image upload code.
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())
While I am uploading a new case, I create the case, add attachments, then patch the newly created case with the new attachment. Again all of this work. I can see the attachment in my case online, however when I download it the file is invalid.
I have attempted to read the data as a byte array as follows:
def convertAttachmentToJsonBinary(attachmentPath):
file = open(attachmentPath, 'rb')
encoded_data = bytearray(file.read())
data = "[" + str(encoded_data) + "]"
return data
I get the same error, uploading the image works however downloading the image it is invalid.
I tested again and found I can't open the url returned from uploading to attachment Rest API successfully. So the image has broken when uploading.
Please try to convert image to byte array with bytearray(image_file.read())
.
Please replace the value of <>
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
......