Dapplo.Confluence
Dapplo.Confluence copied to clipboard
How to add attachment to page
Hi, I am trying to add an image to an existing confluence page. Can you share some code exemple to do so? I'm looking into this functions but I am not sure what is the way to go. thanks
` // what should the content string be? private async Task CreateAttachment(string title, string content, long parentId) { return await _client.Content.CreateAsync(ContentTypes.Attachment, title, SpaceId, content, parentId); }
// how to create a picture Content instance?
private async Task AttachImageToPage(long toPageId, Content image, string filename)
{
var result = await _client.Attachment.AttachAsync(toPageId, image, filename);
return result.FirstOrDefault();
}
`
Ok, I'll make something. Hang-in there, I don't always have time to work on this.
I found this code on stack overflow using rest api that works but it would be nice to have a simple wrapper that offer more parameters maybe.
private string SimpleRestApiUpload(long pageId, string filePath)
{
using (var client = new WebClient())
{
string url = string.Format("{0}/rest/api/content/{1}/child/attachment", DomaineUrl, pageId);
string authString = $"{UserName}:{Password}";
string encodedValue = Convert.ToBase64String(Encoding.ASCII.GetBytes(authString));
client.Headers.Add("Authorization", "Basic " + encodedValue);
client.Headers.Add("X-Atlassian-Token", "nocheck");
byte[] result = client.UploadFile(url, filePath);
return Encoding.Default.GetString(result);
}
}
but attachment update doesn't work with that code.
My underlying framework does most of the work for you! If you have a file on the file system, you can do the following:
using Stream stream = File.OpenRead(@"path to your file");
var attachments = await _client.Attachment.AttachAsync(_toPageId, stream, "myfilename", "Just attached a bitmap");
That's all... (c# 9 syntax, if you can't use that you just need to do a using block around your stream)
Btw. In the case you have a System.Drawing.Bitmap in your code you can do the following:
Somewhere when your application starts, you'd want to make sure that the underlying HttpExtensions works with Bitmaps, you need to call the following ONCE:
BitmapHttpContentConverter.RegisterGlobally(); (assumes using Dapplo.HttpExtensions.WinForms.ContentConverter;) Then you can just attach it directly via:
var attachments = await _client.Attachment.AttachAsync(toPageId, bitmap, "image.png", "Just attached a bitmap"); where bitmap is the variable with the bitmap.
By default the image is stored as a PNG, you can configure this, but I think the first option if what you need.
thanks a lot!
@fredggy Does this mean that works for you?