Forum Discussion

haneefvf's avatar
haneefvf
Copper Contributor
Dec 16, 2021

Create Attachment in Azure Project is not working

Create Attachment in Azure Project is not working. In start attachments are created. but now create black image on every call with same code and same image.

Code sample

    $data = fopen("test.png", 'rb');
    $size = filesize($file);
    $contents = fread($data, $size);
    fclose($data);
    $encodedData = base64_encode($contents);
       
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $header = array("Authorization:Basic ".base64_encode($params['username'].":".$params['token']),"Content-Type:application/octet-stream");

    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    if ($params['request']) {
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($encodedData));
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);

    Response is

    stdClass Object
    (
    [id] => f1f55c9e-8f48-4408-90f0-69ebb3c4d0ff
    )

    When i check url in browser there is showing black image.
  • haneefvf's avatar
    haneefvf
    Copper Contributor

    Solved code Sample

    $data = fopen("test.png", 'rb');
    $size = filesize($file);
    $contents = fread($data, $size);
    fclose($data);

    $url = "https://dev.azure.com/{OrganizationName}/{ProjectId}/_apis/wit/attachments?fileName=test.png&uploadType=simple&api-version=6.0";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $header = array("Authorization:Basic ".base64_encode($params['username'].":".$params['token']),"Content-Type:application/octet-stream");
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $contents);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    $response = json_decode($response);

    Link with workitem

    $postRequest = [];
    $postRequest[] = ["op"=>"add",
    "path"=> ("/relations/-"),
    'from' => null,
    "value"=> ["rel"=>"AttachedFile",
    "url"=>$response->url

    ]
    ];
    $url = "https://dev.azure.com/{OrganizationName}/{ProjectId}/_apis/wit/workitems/{workitemId}?api-version=6.0";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $header = array("Authorization:Basic ".base64_encode($params['username'].":".$params['token']),"Content-Type:application/json-patch+json");
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postRequest));

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

Resources