WasGoodDone WasGoodDone -4 years ago 85
C# Question

How to post image to URL properly?

I'm trying to post an image to the StockTwits API and am receiving a 422 error as a response saying that the image format can't be recognized. The image is a png file, so it should be a valid file format. I've tried using a jpeg with the same response.

Am I encoding the image incorrectly, or missing some configuration in the


public void Share(string text, string imageFilePath)
using(HttpClient client = new HttpClient())
using (MultipartFormDataContent formData = new MultipartFormDataContent())
string url = stocktwitsCreateMessageUrl + "&" +
"body=" + Core.Globals.UrlEncode(twit) + "&" +
"sentiment=" + StockTwitsSentiment.ToString().ToLower();

byte[] imageBytes = File.ReadAllBytes(imageFilePath);
HttpContent imageContent = new ByteArrayContent(imageBytes);
string fileName = Path.GetFileName(imageFilePath);
formData.Add(imageContent, "chart", fileName);
HttpResponseMessage stockTwitsResponse = await client.PostAsync(url, formData);
Stream responseContent = await stockTwitsResponse.Content.ReadAsStreamAsync();
string result = new StreamReader(responseContent).ReadToEnd();
Print(result); // helper method
if (!stockTwitsResponse.IsSuccessStatusCode)
LogErrorResponse(result, stockTwitsResponse);
LogAndPrint(typeof(Custom.Resource), "ShareStockTwitsSentSuccessfully", new[] { Name }, Cbi.LogLevel.Information);



"response": { "status": 422 },

"errors": [ { "message": "We couldn't recognize the image format. Format must be one of: image/jpg image/jpeg image/pjpeg image/png image/x-png image/gif" } ]


Answer Source

Don't forget to set your Content-Type header to "image/png"!

See: https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.contenttype(v=vs.110).aspx

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download