Post File as an Attachment Using Confluence Rest API with PHP curl

Coline Macorol January 31, 2020

Hello All,

I have trying for quite awhile to post a file as an attachment using the rest api with php curl. I have seen similar questions out there, and I tried to emulate those who said they had success, but it just does not seem to work for me. I would greatly appreciate and welcome any suggestions.

 

My code:

$ch = curl_init();
$file = 'C:\path\path\path\path.txt';

if (function_exists('curl_file_create')) {
     $cFile = curl_file_create($file);
} else { 
     $cFile = '@' . realpath($file);
}
$postData = array('file_contents' => $cFile);
$headers = array();
$headers[] = "X-Atlassian-Token: no-check"; 


curl_setopt($ch, CURLOPT_URL, "http://localhost:8090/rest/api/content/31391748/child/attachment");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "****" . ":" . "****");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

$result = curl_exec($ch);
$info = curl_getinfo($ch);
print_r($info);
curl_close ($ch);

 

I noticed I am getting a HTTP code of 400 when $info prints, which I know means it is a bad request. I am not sure what could potentially be causing this. Again, any help will be much appreciated!

2 answers

1 accepted

0 votes
Answer accepted
Thomas Deiler
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
February 2, 2020

Dear @Coline Macorol ,

as written in the API document:

The name of the multipart/form-data parameter that contains attachments must be "file"

Replace

$postData = array('file_contents' => $cFile);

with 

$postData = array('file' => $cFile);

So long

Thomas

Coline Macorol February 4, 2020

Hi Thomas,

Thanks so much for the quick response! I'm very happy to report that it worked! 

 

Cheers,

Coline Macorol

0 votes
Coline Macorol March 20, 2020

Hi all,

I'm unfortunately back to say the php curl is once again not working. Thanks to php curl error handling, it appears the problem is cURL error (26): Failed to open/read local data from file/application.

I know this means it is unable to open the file it is pointing to. However, I don't know why it isn't, especially since it worked before and I haven't changed anything but the file. Could it be the file path? Or is it something else I'm not seeing?

 

Thanks,

Coline Macorol

Suggest an answer

Log in or Sign up to answer
TAGS
AUG Leaders

Atlassian Community Events