1

I am trying to POST image file and a set of parameters using ASP.NET Core. Is there any option/solution to send both Model Data and Image at the same time in POST API. Here is the image of POST API in POSTMAN:

enter image description here

Here is body with Model Information: enter image description here

If I do it like following code then my companyInfo data is null and image is there.

    [HttpPost("PostInformation")]
    public async Task<ActionResult<Company>> PostEmployeeJobCategories(IFormFile image, [FromForm]Company companyInfo)
    {
    }

If I do it like following code then I am getting Unsupported Media Type.

    [HttpPost("PostInformation")]
    public async Task<ActionResult<Company>> PostEmployeeJobCategories([FromForm]IFormFile image, [FromBody]Company companyInfo)
    {
    }

Any Advise, how to achieve the goal ?

Thank You

Jugnu Khan
  • 63
  • 3
  • 9

2 Answers2

2

Adding [FromForm] attribute and sending everything through form-data tab in Postman works for me:

public class OtherData
{
    public string FirstString { get; set; }
    public string SecondString { get; set; }
}
public async Task<IActionResult> Post(IFormFile file, [FromForm]OtherData otherData)
{
     return Ok();
}

postman view

As vahid tajari pointed out, you can also add your IFormFile to the class definition.

del
  • 43
  • 1
  • 7
  • No, it didnt help – Jugnu Khan Aug 17 '20 at 10:43
  • Thanks a lot, but i have tons of parameters to pass, like Company General Information, then Multiple Company Business Types for each Company, Multiple Contact Persons for each company, Multipe facility Types which are one to many...so is there any other solution you can suggest ? All of this information is in BODY and Image file is in form-data. So please advise accordingly – Jugnu Khan Aug 17 '20 at 11:08
  • Nothing comes to my mind in that case. Maybe this will help you https://stackoverflow.com/questions/4083702/posting-a-file-and-associated-data-to-a-restful-webservice-preferably-as-json – del Aug 17 '20 at 11:24
0

In asp.net core, you can send file and data together, so change your model to:

 public class Company
    {
        public IFormFile Image { get; set; }
        public string NameEn { get; set; }
        public string Address { get; set; }
        //......
    }

And your action method to:

[HttpPost("PostInformation")]
public async Task<ActionResult<Company>>PostEmployeeJobCategories([FromForm] Company companyInfo)
      {
      }
vahid tajari
  • 1,163
  • 10
  • 20