Failed to create the attachment

ShivanandaR
Giga Contributor

I am unable to attach the file during the web API call.

Getting below error. Pls help

Failed to create the attachment. File part might be missing in the request.

 

 

using (HttpClient client = new HttpClient())
{
// Set the base address for HttpClient
client.BaseAddress = new Uri(serviceNowInstance);

// Add authentication headers
var byteArray = Encoding.ASCII.GetBytes($"{username}:{password}");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

// Read file data asynchronously
byte[] fileData = await File.ReadAllBytesAsync(filePath);

// Create a multipart form data content
var form = new MultipartFormDataContent();
form.Add(new StringContent("incident"), "table_name");
form.Add(new StringContent("1234"), "table_sys_id");

// Add the file content
//var fileContent = new ByteArrayContent(fileData);
//fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("octet-stream");
//form.Add(fileContent, "file", fileName);

var myBinaryData = new byte[100];
Random.Shared.NextBytes(myBinaryData);
var binaryContent = new ByteArrayContent(myBinaryData);
binaryContent.Headers.ContentType = new("application/octet-stream");
form.Add(binaryContent, "binary");


using var openReadStream = File.OpenRead(filePath);

// Send the POST request
HttpResponseMessage response = await client.PostAsync("https://test/upload", form);

// Check if the request was successful
if (response.IsSuccessStatusCode)
{
string responseData = await response.Content.ReadAsStringAsync();
Console.WriteLine("Success: " + responseData);
}
else
{
string error = await response.Content.ReadAsStringAsync();
Console.WriteLine("Error: " + response.StatusCode + " " + error);
}

}

0 REPLIES 0