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....
I followed the example I found here
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;
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.