Home > Software engineering >  Send IFormFile to the rest endpoint using http client
Send IFormFile to the rest endpoint using http client

Time:01-08

I have endpoint which accepts IFormFile file

[HttpPost]
public async Task<ActionResult<MyResponse>> Post([FromRoute] MyRequest request, CancellationToken cancellationToken = default)
{
       ...
}
public class MyRequest 
{
   [FromForm]
   public IFormFile File { get; set; }     

   [FromRoute(Name = "userId")]
   public string UserId{ get; set; }
}

on the client side I have simple IFormFile

var bytes = Encoding.UTF8.GetBytes("This is a dummy file");
IFormFile file = new FormFile(new MemoryStream(bytes), 0, bytes.Length, "File", "dummy.txt");

how can I send this IFormFile to the above post endpoint using http client?

What have I tried?

var url = "";
var streamContent = new StreamContent(file.OpenReadStream(), 4069);
var httpClient = new HttpClient();
await httpClient.PostAsync($"{url}", streamContent);

CodePudding user response:

You should pass the streamContent into MultipartFormDataContent.

var streamContent = new StreamContent(file.OpenReadStream());
streamContent.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType);
streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
    Name = "file",
    FileName = file.FileName
};

MultipartFormDataContent formData = new MultipartFormDataContent();
formData.Add(streamContent);

var httpClient = new HttpClient();
await httpClient.PostAsync($"{url}", formData);

Demo

enter image description here

  • Related