beatsforthemind
beatsforthemind

Reputation: 877

File attachment with Jira REST API returns empty array

I am building a script in PHP that will will attach a file to an existing Jira issue. When running the script all that is returned is an empty array. I am wondering what is wrong with my code:

$cfile = curl_file_create($_SERVER['DOCUMENT_ROOT'].'/test.png','image/png','test.png');

$data1 = array('test.png' => $cfile);

$url1 = 'http://myserver.com/rest/api/2/issue/TP-55/attachments';
$ch1 = curl_init();
$headers1 = array(
    'Content-Type: multipart/form-data',
    'X-Atlassian-Token: nocheck'
);

curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch1, CURLOPT_VERBOSE, 1);
curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch1, CURLOPT_HTTPHEADER, $headers1);
curl_setopt($ch1, CURLOPT_CUSTOMREQUEST, "POST");

curl_setopt($ch1, CURLOPT_SAFE_UPLOAD, 1);
curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, 1);

curl_setopt($ch1, CURLOPT_POSTFIELDS, $data1);
curl_setopt($ch1, CURLOPT_URL, $url1);

$username = 'myusername';
$password = 'mypassword';
curl_setopt($ch1, CURLOPT_USERPWD, "$username:$password");

$result1 = curl_exec($ch1);
$ch_error1 = curl_error($ch1);


if ($ch_error1) {
    echo "cURL Error: $ch_error1";
} else {
    echo $result1;
}

curl_close($ch1);

With this code I am just attempting to upload a test file that is already on the server. What would I need to change to complete a successful file upload?

Upvotes: 3

Views: 1609

Answers (1)

Alex Robert
Alex Robert

Reputation: 103

Add one or more attachments to an issue. This resource expects a multipart post. The media-type multipart/form-data is defined in RFC 1867. Most client libraries have classes that make dealing with multipart posts simple. For instance, in Java the Apache HTTP Components library provides a MultiPartEntity that makes it simple to submit a multipart POST. In order to protect against XSRF attacks, because this method accepts multipart/form-data, it has XSRF protection on it. This means you must submit a header of X-Atlassian-Token: nocheck with the request, otherwise it will be blocked. The name of the multipart/form-data parameter that contains attachments must be "file" A simple example to upload a file called "myfile.txt" to issue REST-123: curl -D- -u admin:admin -X POST -H "X-Atlassian-Token: nocheck" -F "[email protected]" .../rest/api/2/issue/TEST-123/attachments

so the data you transmit must contain a field name file [email protected]. se example above

Upvotes: 1

Related Questions