Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding attachment to Jira via API

I am using Jira's API to add an attachment file to a case. My issue is after my code attaches a file, and I go to the JIRA case to confirm, I see two things. First, if it is an image, I can see a thumbnail of the image. If I click it, though, I get an error saying "The requested content cannot be loaded. Please try again." Second, under the thumbnail, instead of showing the name of the file, it has the path that the file was originally uploaded from (id: c:/wamp/www/...." Is there a reason this is happening? Here is my code:

$ch = curl_init();
$header = array(
  'Content-Type: multipart/form-data',
   'X-Atlassian-Token: no-check'
);
$attachmentPath = $this->get_file_uploads();
//$attachmentPath comes out to be something like:
//c:/wamp/www/mySite/web/system/files/my_folder/DSC_0344_3.JPG

$data = array('file'=>"@". $attachmentPath, 'filename'=>'DSC_0344_3.JPG');
$url= 'https://mysite.atlassian.net/rest/api/2/issue/20612/attachments/';

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch,  CURLOPT_POSTFIELDS ,$data);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "myusername:mypassword");

$result = curl_exec($ch);
$ch_error = curl_error($ch);

Once the file gets added to Jira, when I log into jira, I can see the thumbnail but the title under the file is something like: c:/wamp/www/mySite/web/system/files/my_folder/DSC_0344_3.JPG instead of the file name.

thanks

like image 899
jason Avatar asked Jan 22 '15 00:01

jason


1 Answers

You need to use:

$data = array('file'=>"@". $attachmentPath . ';filename=DSC_0344_3.JPG');

It is an issue in PHP cURL <5.5.0 but > 5.2.10, see JIRA API attachment names contain the whole paths of the posted files

When using PHP >= 5.5.0 it is better to switch to the CURLFile approach as also documented in that link.

$cfile = new CURLFile($attachmentPath);
$cfile->setPostFilename('DSC_0344_3.JPG');
$data = array('file'=>$cfile);
like image 148
Hans Z. Avatar answered Sep 26 '22 01:09

Hans Z.