Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post form-data IFormFile with HttpClient?

I have backend endpoint Task<ActionResult> Post(IFormFile csvFile) and I need to call this endpoint from HttpClient. Currently I am getting Unsupported media type error. Here is my code:

var filePath = Path.Combine("IntegrationTests", "file.csv");
var gg = File.ReadAllBytes(filePath);
var byteArrayContent = new ByteArrayContent(gg);
var postResponse = await _client.PostAsync("offers", new MultipartFormDataContent
{
    {byteArrayContent }
});
like image 815
Deivydas Voroneckis Avatar asked Mar 29 '19 08:03

Deivydas Voroneckis


People also ask

What is IFormFile C#?

What is IFormFile. ASP.NET Core has introduced an IFormFile interface that represents transmitted files in an HTTP request. The interface gives us access to metadata like ContentDisposition, ContentType, Length, FileName, and more. IFormFile also provides some methods used to store files.


2 Answers

You need to specify parameter name in MultipartFormDataContent collection matching action parameter name (csvFile) and a random file name

var multipartContent = new MultipartFormDataContent();
multipartContent.Add(byteArrayContent, "csvFile", "filename");
var postResponse = await _client.PostAsync("offers", multipartContent);

or equivalent

var postResponse = await _client.PostAsync("offers", new MultipartFormDataContent {
    { byteArrayContent, "csvFile", "filename" }
});
like image 199
Alexander Avatar answered Sep 19 '22 13:09

Alexander


Use this snippet:

const string url = "https://localhost:5001/api/Upload";
const string filePath = @"C:\Path\To\File.png";

using (var httpClient = new HttpClient())
{
    using (var form = new MultipartFormDataContent())
    {
        using (var fs = File.OpenRead(filePath))
        {
            using (var streamContent = new StreamContent(fs))
            {
                using (var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync()))
                {
                    fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");

                    // "file" parameter name should be the same as the server side input parameter name
                    form.Add(fileContent, "file", Path.GetFileName(filePath));
                    HttpResponseMessage response = await httpClient.PostAsync(url, form);
                }
            }
        }
    }
}
like image 43
Moien Tajik Avatar answered Sep 17 '22 13:09

Moien Tajik