Search code examples
c#asp.net.net-coreasp.net-core-webapimultipartform-data

C# How to post an entity with a file as form-data from HttpClient to API?


I've got an ASP.NET Core API that receives an entity like this:

public class ChartDTO
{
    public string Name { get; set; }
    //public byte[] Image { get; set; }
    public IFormFile Image { get; set; }
}

The API controller is:

     [HttpPost]
    [Route("[action]")]
    public ActionResult Register([FromForm] ChartDTO dto) // Using IFormFile
    {
        if (dto.Image.Length > 0)
        {
            var filePath = Path.Combine("wwwroot\\Charts", dto.Name);
            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                try
                {
                    dto.Image.CopyTo(fileStream);
                    return Ok(new { status = true, message = "Chart posted Successfully" });
                }
                catch (Exception)
                {
                    return BadRequest();
                }
            }
        }
        return BadRequest();
    }

It works great from Postman (Body = form-data, Name = "DEV.png", Image = the file), but I can not figure out how to replicate this in a console app. Found lots of similar question, but they all seem to focus on uploading a single file only and I need an entity. A Base64 byte array is an option for the image, but I couldn't get that to work either.


Solution

  • Try this, it works fine for me. You have to define a MultipartFormDataContent

    var requestContent = new MultipartFormDataContent(); 
    var imageContent = new ByteArrayContent(ImageData);
    
    requestContent.Add(imageContent, "image", "image.jpg");
    
    await client.PostAsync(url, requestContent);