通过 API 向 Jira 添加附件


Adding attachment to Jira via API

我正在使用 Jira 的 API 向案例添加附件文件。 我的问题是在我的代码附加一个文件后,我去 JIRA 案例确认,我看到了两件事。 首先,如果是图像,我可以看到图像的缩略图。 但是,如果我单击它,则会收到一条错误消息,指出"无法加载请求的内容。 请再试一次。 其次,在缩略图下,它不显示文件名,而是具有文件最初上传的路径(id:c:/wamp/www/...." 发生这种情况有什么原因吗?这是我的代码:

$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);

将文件添加到 Jira 后,当我登录 Jira 时,我可以看到缩略图,但文件下的标题类似于:c:/wamp/www/mySite/web/system/files/my_folder/DSC_0344_3.JPG 而不是文件名。

谢谢

您需要使用:

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

这是 PHP cURL <5.5.0 中的一个问题,但在 5.2.10>,请参阅 JIRA API 附件名称包含已发布文件的整个路径

使用 PHP>= 5.5.0 时,最好切换到该链接中也记录的CURLFile方法。

$cfile = new CURLFile($attachmentPath);
$cfile->setPostFilename('DSC_0344_3.JPG');
$data = array('file'=>$cfile);

对于未来的任何人:这是我写的一个适用于 PHP 7 的函数

function attachFileToIssue($issueURL, $attachmentURL) {
// issueURL will be something like this: http://{yourdomainforjira}.com/rest/api/2/issue/{key}/attachments 
// $attachmentURL will be real path to file (i.e. C:'hereswheremyfilelives'fileName.jpg) NOTE: Local paths ("./fileName.jpg") does not work!
$ch = curl_init();
$headers = array(
    'X-Atlassian-Token: nocheck',
    'Content-type: multipart/form-data'
);
$cfile = new CURLFile($attachmentURL);
$cfile->setPostFilename(basename($attachmentURL));
$data = array("file" => $cfile);
curl_setopt_array(
    $ch,
    array(
        CURLOPT_URL => $issueURL,
        CURLOPT_VERBOSE => 1,
        CURLOPT_POSTFIELDS => $data,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => 1,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_USERPWD => "{username}:{password}"
    )
);
$result = curl_exec($ch);
$ch_error = curl_error($ch);
if ($ch_error)
    echo "cURL Error: " . $ch_error;
curl_close($ch);

}