I'm trying to create a new creative through API using C# and httpclient.
But don't know how to pass parameters and file at the same time using MultipartFormDataContent.
Is there any example for this?
My code looks like this, but it doesnt work and get internal error. (No response content to say where it was wrong).
var content = new MultipartFormDataContent();
// parameters without image_file
var serializedString = JsonConvert.SerializeObject(newCreative,
Formatting.None, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
}
);
var sc = new StringContent(serializedString, Encoding.UTF8, "application/json");
content.Add(sc);
// for image_file
using (var memoryStream = new MemoryStream())
{
newCreative.ImageFile.CopyTo(memoryStream);
var fileContent = new ByteArrayContent(memoryStream.ToArray());
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
Name = "image_file",
FileName = Path.GetFullPath(newCreative.ImageFile.FileName)
};
fileContent.Headers.Add("Content-Type", "image/jpeg");
content.Add(fileContent, "image_file");
}
try
{
var client = new HttpClient()
{
};
client.DefaultRequestHeaders.Add("Authorization", apiKey);
var path = "creatives.json";
var responseResult = await client.PostAsync(path, content);
if (responseResult.IsSuccessStatusCode)
return true;
else
return false;
}
catch (Exception e)
{
return false;
}
If I use content like this, will give an error response, but it says can't find the type.
(Seems the format to wrap the stringcontent into the MultipartFormDataContent is wrong).
var content = new MultipartFormDataContent();
content.Add(new StringContent("banner"),"type");
//use this to call the httpclient...