You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于C# REST API实现SharePoint Online与Confluence Cloud同步失败求助

Confluence Cloud API上传附件报错415/500的解决办法

问题根源

从你提供的错误信息可以明确:Confluence Cloud的附件上传API要求请求体必须是multipart/form-data或multipart/mixed格式,而你的代码用ByteArrayContent直接传递二进制数据,要么指定application/octet-stream触发415(不支持的媒体类型),要么默认类型不符合要求触发500错误。

修正后的代码

private static async Task<string> UploadAttachmentToConfluence(string Username, string APIKey)
{
    string filePath = @"C:\TestDocument.docx";
    string fileName = Path.GetFileName(filePath);
    // 根据文件类型设置正确的Content-Type,docx示例如下,其他类型需对应调整
    string fileContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";

    using (HttpClient httpClient = new HttpClient())
    {
        // 设置基础认证
        string authToken = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes($"{Username}:{APIKey}"));
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authToken);
        httpClient.DefaultRequestHeaders.Add("X-Atlassian-Token", "nocheck");

        // 构造符合要求的multipart请求体
        using (var multipartContent = new MultipartFormDataContent())
        using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            var fileContent = new StreamContent(fileStream);
            fileContent.Headers.ContentType = new MediaTypeHeaderValue(fileContentType);
            // 参数名必须为"file",这是Confluence API的固定要求
            multipartContent.Add(fileContent, "file", fileName);

            var requestUri = "https://test.atlassian.net/wiki/rest/api/content/264966/child/attachment";
            HttpResponseMessage response = await httpClient.PostAsync(requestUri, multipartContent);
            
            // 处理响应结果
            if (response.IsSuccessStatusCode)
            {
                string responseContent = await response.Content.ReadAsStringAsync();
                return responseContent;
            }
            else
            {
                string errorContent = await response.Content.ReadAsStringAsync();
                throw new HttpRequestException($"上传失败: {response.StatusCode}\n错误详情: {errorContent}");
            }
        }
    }
}

关键修改说明

  • 请求体格式替换:用MultipartFormDataContent替代ByteArrayContent,完全匹配Confluence API对上传请求的格式要求
  • 正确设置文件Content-Type:根据上传文件的实际类型指定对应的MIME类型(比如图片用image/png,表格用application/vnd.openxmlformats-officedocument.spreadsheetml.sheet),比通用的application/octet-stream更规范
  • 移除URL中的file-name参数:文件名通过Multipart表单的fileName参数传递即可,无需在URL中额外指定
  • 异常处理优化:修复原代码中返回类型不匹配的问题(原方法返回string却返回OkObjectResult),改为抛出异常或返回错误信息,逻辑更合理

额外注意事项

  • 确保目标页面ID(264966)存在且你拥有编辑权限
  • 如果需要覆盖已存在的同名附件,可在请求URL后添加?allowDuplicate=false参数

内容的提问来源于stack exchange,提问作者Aman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 23:15:44