Forums

Articles
Create
cancel
Showing results for 
Search instead for 
Did you mean: 

How to Upload an Attachment to Confluence Page using PowerShell and REST API?

Boris_PS1
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
August 28, 2017

Does anybody know, How to Upload an Attachment to Confluence Page using PowerShell and REST API?

I have an example on Confluence documentation on CURL:

curl -v -S -u admin:admin -X POST -H "X-Atlassian-Token: no-check" -F "file=@myfile.txt" -F 
"comment=this is my file" "http://localhost:8080/confluence/rest/api/content/3604482/child/attachment" 
| python -mjson.tool

But I'm a bit stuck on converting it to PowerShell in a correct way. 

Please advice....

1 answer

1 accepted

1 vote
Answer accepted
DarkSideMilk
Contributor
November 29, 2017

I followed the example I found here

https://community.developer.atlassian.com/t/powershell-invoke-restmethod-uploading-new-attachment-to-jira-ticket/6184/2

 

The more detailed answer would involve saying that the multipart-form content type doesn't work with invoke-restmethod, at least not in the way confluence/jira needs it to.

So you use a different method that is similar, it still requires a idictionary/hash table powershell object for the headers. And it needs the api uri for the attachment of a page. 

Here, let me just show you an example complete with creating a base64 encoded string for the authorization header, formatting got messed up in copying though.

function Add-AttachmentToPage { 
[CmdletBinding()]
param (
[string]$baseUrl, #base url to create the api uri from, no trailing slash
[string]$pageId, #id of the page in confluence
[string]$filePath, #path to the file to upload
[string]$authToken #base64 encoded string of username:password
)

begin {
Write-Host "creating uri and web client for file upload"
$uri = "$baseUrl/rest/api/content/$pageId/child/attachment";
$webClient = New-Object System.Net.WebClient;
$webClient.Headers.Add('X-Atlassian-Token','no-check');
$webClient.Headers.Add('Authorization',"Basic $authToken");
}

process {
Write-Host "Uploading $filePath confluence page of id $pageId via uri $uri";
$webClient.UploadFile($uri,$filePath);
}


end {
Write-Host "$filePath attached to confluence page of id $pageId";
return;
}
}

function
Convert-StringToBase64 {
[CmdletBinding()]
param ( $Text )
begin { $Bytes = [System.Text.Encoding]::Unicode.GetBytes($Text) }
process { $EncodedText =[System.Convert]::ToBase64String($Bytes) }
end { return $EncodedText }
}

$
authToken = Convert-StringToBase64 -Text 'username:password';

Add-AttachmentToPage
-baseUrl 'https://YOURCONFLUENCEURL' -pageId 123 -filePath '\\path\to\file' -authToken $authToken;

Suggest an answer

Log in or Sign up to answer
TAGS
AUG Leaders

Atlassian Community Events