I'm receiving a IFormFile
object from an API POST request, and I'm trying to pass that file through to another API endpoint via a POST request with some JSON attached.
I am able to embed the image inside the request, but the server I'm sending to always returns a 500. I believe the issue the fact that I'm sending the JSON and the IFormFile
together, as when I send one or the other it works okay (albeit, I'm not receiving the 200 response I want due to one or the other being missing).
Here is the code I'm using to post the data:
public async Task<APIResponse<T>> PostForm<T>(string baseURL, string apiName, IFormFile file, string jsonToPost = "", Dictionary<string, string> headers = null) where T : class
{
using (var client = new HttpClient() { BaseAddress = new Uri(baseURL) })
{
client.BaseAddress = new Uri(baseURL);
HttpResponseMessage response = null;
if (headers != null)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
try
{
var multiContent = new MultipartFormDataContent();
var fileStreamContent = new StreamContent(file.OpenReadStream());
multiContent.Add(fileStreamContent, "file", file.FileName);
multiContent.Add(new StringContent(jsonToPost,System.Text.Encoding.UTF8, "application/json"));
response = await client.PostAsync(apiName, multiContent);
return new APIResponse<T>(JsonConvert.DeserializeObject<T>(await response.Content.ReadAsStringAsync()), null, (int)response.StatusCode);
}
catch
{
return new APIResponse<T>(null, await response.Content.ReadAsStringAsync(), (int)response.StatusCode);
}
}
}
And here is what the JSON looks like if it helps anyone:
{
"orderId": 694532,
"type": "4x6",
"copies": 1,
"sizing": "Crop",
"priceToUser": 4000,
"md5hash": "5fed252e505f8542b38d9c0b1f221a71"
}
Edit - Updated code:
public async Task<APIResponse<T>> PostForm<T>(string baseURL, string apiName, IFormFile file, string jsonToPost = "", Dictionary<string, string> headers = null) where T : class
{
var client = new HttpClient();
client.BaseAddress = new Uri(baseURL);
HttpResponseMessage response = null;
if (headers != null)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
try
{
var multiContent = new MultipartFormDataContent();
multiContent.Add(new StringContent(jsonToPost,System.Text.Encoding.UTF8, "application/json"));
multiContent.Add(GetByteArray(file), "file", file.FileName);
response = await client.PostAsync(apiName, multiContent);
return new APIResponse<T>(JsonConvert.DeserializeObject<T>(await response.Content.ReadAsStringAsync()), null, (int)response.StatusCode);
}
catch
{
return new APIResponse<T>(null, await response.Content.ReadAsStringAsync(), (int)response.StatusCode);
}
}
private ByteArrayContent GetByteArray(IFormFile file){
byte[] data;
var br = new BinaryReader(file.OpenReadStream());
data = br.ReadBytes((int)file.OpenReadStream().Length);
return new ByteArrayContent(data);
}