[SOLVED] model value displays null when [FromForm] is posted with image file in web api controller

Issue

My API is as below. I am trying to post model value wth image file using postman. But, model value did not bind. How to post json data with image file using POSTMAN?

[HttpPost]
   [Route("api/images_upload")]
   public IActionResult UploadImages([FromForm] Chapter chapter,IFormFile file)
   {
       try
       {

           var fileName = Path.GetFileName(file.FileName);
           var absoluteFileName = fileName.Replace(fileName, Guid.NewGuid().ToString());
           var extension = Path.GetExtension(fileName);
           var fullFileName = string.Concat(absoluteFileName, extension);

           var physicalPath = Path.Combine(HostingEnvironment.WebRootPath, "images", fullFileName);

           file.CopyTo(new FileStream(physicalPath, FileMode.Create));
           return Content("Images Uploaded");
       }
       catch (Exception ex)
       {
           throw ex;
       }

   }

Solution

For posting Chapter and IFormFile file, you could try to post with form-data in PostMan.

For posting IFormFile, you could not pass it through application/json content type. And when posting form-data, you should not add Content-Type as application/json, otherwise, the .net core will try JsonFormatter to bind the request body to model instead of FromForm, then chapter will be null.

Here is a working PostMan demo.

enter image description here

Note, there is no Content-Type header.

Answered By – Edward

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *