Learner
Learner

Reputation: 1315

JIRA REST API how to add attachment using c#

I am using jira api to add attachment to the issue

According to documentation i have set few things.

  1. submit a header of X-Atlassian-Token: nocheck with the request.

  2. The name of the multipart/form-data parameter that contains attachments must be "file".

  3. resource expects a multipart post.

& when i run my code i get internal server error.

my code is as follows

string postUrl = "http://localhost:8080/rest/api/latest/issue/TES-99/attachments";
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); 
client.DefaultRequestHeaders.Add("X-Atlassian-Token", "nocheck");
client.BaseAddress = new System.Uri(postUrl);
byte[] cred = UTF8Encoding.UTF8.GetBytes(credentials);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
var content = new MultipartFormDataContent();
var values = new[]
{
    new KeyValuePair<string, string>("file", "e:\\z.txt")               
};
foreach (var keyValuePair in values)
{
    content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
}
            
var result = client.PostAsync(postUrl, content).Result;

please suggest where i am making mistake

Upvotes: 3

Views: 4701

Answers (2)

agenc
agenc

Reputation: 322

This is my working code.

   [HttpPost]
   public async Task<IActionResult> CreateTicketWithAttachent(IFormFile file, [FromQuery] string issuekey)
    {
        try
        {
            string url = $"http://jiraurl/rest/api/2/issue/{issuekey}/attachments";
            var client = new HttpClient();
            var header = new AuthenticationHeaderValue("Basic", "your-auth-key");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Authorization = header;
            client.DefaultRequestHeaders.Add("X-Atlassian-Token", "no-check");

            MultipartFormDataContent multiPartContent = new MultipartFormDataContent("-data-");

            ByteArrayContent byteArrayContent;
            using (var ms = new MemoryStream())
            {
                file.CopyTo(ms);
                var fileBytes = ms.ToArray();
                //string fileString = Convert.ToBase64String(fileBytes);
                byteArrayContent = new ByteArrayContent(fileBytes);
            }

            multiPartContent.Add(byteArrayContent, "file", file.FileName);

            var response = await client.PostAsync(url, multiPartContent);

            var result = response.Content.ReadAsStringAsync().Result;

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
                throw new Exception(result);

            return Ok();
        }
        catch (Exception e)
        {
            return BadRequest(e);               
        }
    }

Upvotes: 0

Learner
Learner

Reputation: 1315

I solved this too. now i am able to add attachment using JIRA API with C#.

i was making mistake with this piece of code.

var values = new[]
{
    new KeyValuePair<string, string>("file", "e:\\z.txt")               
};

foreach (var keyValuePair in values)
{
    content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
}

this is my code.

string postUrl = "http://localhost:8080/rest/api/latest/issue/" + projKey + "/attachments";
      
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();

client.DefaultRequestHeaders.Add("X-Atlassian-Token", "nocheck");
client.BaseAddress = new System.Uri(postUrl);
byte[] cred = UTF8Encoding.UTF8.GetBytes(credentials);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));                                                     
MultipartFormDataContent content = new MultipartFormDataContent();

**//The code which solved the problem**  

HttpContent fileContent = new ByteArrayContent(File.ReadAllBytes(filePath));
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(mimeType);
content.Add(fileContent, "file",fileName);
var result = client.PostAsync(postUrl, content).Result;

Upvotes: 4

Related Questions