I am using HttpClient to upload a file to a WebAPI resource using the code below. Since I am using MultipartFormDataContent, the request message content type is set to multipart/form-data. In WebAPI, I am checking the content header to only allow text/plain media type. So, where do I set the content header for the file type if I am using HttpClient with MultipartFormDataContent.
try
{
var content = new MultipartFormDataContent();
string filePath = Server.MapPath("~/Content/" + "demo.txt");
var filestream = new FileStream(filePath, FileMode.Open);
var fileName = System.IO.Path.GetFileName(filePath);
content.Add(new StreamContent(filestream), "file", fileName);
var requestMessage = new HttpRequestMessage()
{
Method = HttpMethod.Post,
Content = content,
RequestUri = new Uri("http://localhost:64289/api/uploads/"),
};
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Accept", "application/json");
HttpResponseMessage response = await client.SendAsync(requestMessage);
if (response.IsSuccessStatusCode)
{
///
}
}
catch (Exception e)
{
throw;
}
You can set ContentType property by using Headers property of StreamContent object, for example, in my case I am uploading an image and use following code:
StreamContent image = new StreamContent(fileStream);
image.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(imagePath));
You can set ContentType use following code :
var formData = new MultipartFormDataContent();
var bytes = await video.GetBytes();
var streamContent = new StreamContent(new MemoryStream(bytes));
streamContent.Headers.Add("Content-Type", video.ContentType);
streamContent.Headers.Add("Content-Disposition", $"form-data; name=\"{video.FileName}\"; filename=\"{video.FileName}\"");
formData.Add(streamContent, "file", $"{video.FileName}");
var request = new HttpRequestMessage(HttpMethod.Post, $"api/client/uploadVideo?deviceOs={deviceOs}")
{
Content = formData,
};
request.Headers.Add("accept", "application/json");
var response = await httpClient.SendAsync(request);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With