Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the ContentType header when sending MultipartFormDataContent using HttpClient

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;
}
like image 643
user2813261 Avatar asked Oct 23 '14 21:10

user2813261


2 Answers

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));
like image 156
Girish Jain Avatar answered Nov 16 '22 15:11

Girish Jain


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);
like image 38
Omid Rafiee Avatar answered Nov 16 '22 14:11

Omid Rafiee