3
votes

I am using Javascript (jQuery) to do a POST to Azure DevOps rest API to upload a simple image. But, I can't manage to get it working.

There isn't much detailed documentation at https://docs.microsoft.com/en-us/rest/api/azure/devops/wit/attachments/create?view=azure-devops-rest-5.0#upload_a_binary_file apart from understanding I we need to do a post to this endpoint.

POST https://dev.azure.com/fabrikam/_apis/wit/attachments?fileName=imageAsFileAttachment.png&api-version=5.0 

Here is my current code. I can't figure out how do I send my image over to this endpoint? My image exists in a data-uri format.

var dataURI = $("img#target").attr("src");
    var url = "https://xxx.visualstudio.com/_apis/wit/attachments?fileName=image.jpg&api-version=5.0";

    jQuery.ajax ({
        url: url,
        type: "POST",
        data: dataURI,
        processData: false,
        contentType: "application/octet-stream;charset=utf-8",
        success: function(data){
            console.log(data);
        }
    });

Help appreciated!

1

1 Answers

0
votes

I succeeded to upload an image with PowerShell, the script is:

$image = [System.IO.File]::ReadAllBytes("path/to/image.png")
$apiUrl = https://dev.azure.com/_apis...."
$user = ""
$pat = "my-PAT-here"
$base64authInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user, $pat)))
Invoke-RestMethod -Uri $apiUrl -Method Post -Body $image -Headers @{Authorization=("Basic {0}" -f $base64authInfo) } -ContentType application/json (works also with application/octet-stream)

So, the idea is to get the image as bytes array (as binary) and then put it in the body request.

The format you tried to upload is dataURI, try to convert it to Binary, check this code snippet.