How to POST attachment to JIRA using REST API?

后端 未结 4 519
無奈伤痛
無奈伤痛 2021-01-02 11:33

How to POST attachment to JIRA using JIRA REST API and HttpWebRequest in C#?

From the documentation under /rest/api/2/issue/{issueIdOrKey}/attachment

4条回答
  •  甜味超标
    2021-01-02 12:06

    I really didn't want to deal with all that boundary stuff, so here's my shot at it. This works against Confluence whose API looks identical to Jira.

    Thanks to Michael Teper at ASP.NET WebApi: how to perform a multipart post with file upload using WebApi HttpClient and Jeff Caron (above).

    var contents = "some long HTML that I wanted to upload";
    var fileName = "Some fancy file name.html";
    
    using (var client = new HttpClient())
    {
        var uri = new Uri(URL);
    
        client.BaseAddress = new Uri(URL);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
        client.DefaultRequestHeaders.Authorization = authorization;
        client.DefaultRequestHeaders.Add("X-Atlassian-Token", "nocheck");
    
        var uriPath = String.Format(AttachmentPath, pageId);
    
        var content = new MultipartFormDataContent();
        var fileContent = new StringContent(contents);
        // also tested to work: 
        // var fileContent = new ByteArrayContent(Encoding.UTF8.GetBytes(contents));
        content.Add(fileContent, "file", fileName);
    
        var response = await client.PostAsync(uriPath, content);
        if (response.IsSuccessStatusCode)
        {
            return TaskResult.Success(null, response.ReasonPhrase);
        }
        else
        {
            return TaskResult.Failure("Service responded with Status Code: " + response.StatusCode + Environment.NewLine + "Reason Phrase: " + response.ReasonPhrase);
        }
    }
    

提交回复
热议问题