Postman send both data in json and image

Viewed 1518

I have created one API and it is adding data in database, with values and image.

In postman I am calling that and setting image in form-data and other values in raw in JSON but still in image I am getting null value in source code object. Below are screenshots.

I want help in two things :

  1. Why I am getting Null in image value in source code, please check below image.
  2. How can I send both image and data using postman, check below screenshots is that ok what I have tried ?

First screenshot is of postman in which I am sending data in json format :

enter image description here

Second screenshot is of postman in which I am sending image in same request in postman

enter image description here

Now in third image you can see in Image it is showing Null instead of values.

enter image description here

So I am not getting why image is coming null..Below is code for this

public async Task<int> Create(UserPreference _object)
{
   if(_object.Image != null)
   {
       var webRootPath = hostingEnv.WebRootPath;
       var fileName = Path.GetFileName(_object.Image.FileName);
       var filePath = Path.Combine(hostingEnv.WebRootPath, "images\\User", fileName);

       using(var fileStream = new FileStream(filePath, FileMode.Create))
       {
          await _object.Image.CopyToAsync(fileStream);
       }

       _object.ImagePath = filePath;
   }
   
   var obj = await applicationDbContext.UserPreferences.AddAsync(_object);
   return applicationDbContext.SaveChanges();
}

enter image description here

[HttpPost]
[Route("CreateUserPreference")]
public async Task<ActionResult> CreateUserPreference([FromBody] UserPreference userPreference)
{
   if (ModelState.IsValid)
   {
      try
      {
         var userPreferenceId = await _userPreference.Create(userPreference);
         if (userPreferenceId > 0)
             return Ok("User Preference has added");
      }
      catch(Exception)
      {
         return BadRequest();
      }
  }
  return BadRequest();
}


 [Display(Name = "Name")]
        public string Name { get; set; } = "";

        [Display(Name = "Location")]
        public string Location { get; set; } = "";

        [Display(Name = "Date of Birth")]
        public DateTime DateOfBirth { get; set; }

        [Display(Name = "About Me")]
        public string AboutMe { get; set; } = "";

        [Display(Name = "Match Preference")]
        public string MatchPreference { get; set; } = "";

        [Display(Name = "Play Score")]
        public string PlayScore { get; set; } = "";

        [Display(Name = "Location")]
        public string LocationPreference { get; set; } = "";

        [Display(Name = "CreatedOn"), DataType(DataType.Date)]
        public DateTime CreatedOn { get; set; } = DateTime.Now;

        [Display(Name ="Upload Photo")]
        public string ImagePath { get; set; } = "";
        
        [NotMapped]
        public IFormFile Image { get; set; }

        [ForeignKey("User")]
        public int UserId { get; set; }
        public virtual User User { get; set; }
4 Answers

enter image description hereYou cannot send both form-data and JSON body at the same time To solve your problem send image and your other information as form-date For more details see the screenshot

To send image and data using Postman you have to use form-data content type.

Select body => form-data. Column key has a selector. For a file select file-type and select file. To send data in the same time you will have to separate your json in key value pair.

And remove [FromBody] attribute from the action. It is only used for Content-Type: application/json, but yours Content-Type: multipart/form-data;

Postman doesn't allow you to send two different form types at the same time like that. In your question is either sending the JSON payload or the binary content of your image.

So instead, add both the file and the JSON payload to the form-data screen, like this:

enter image description here

Postman will automatically set the Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW header and then handle the actually body like this:

----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="image"; filename="/C:/Users/xyz/Downloads/hystrix-dashboard-netflix-api-example-iPad.png"
Content-Type: image/png

(data)
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="data"

[ASP.NET CORE FRAMEWORK]

Suppose you want to send a file (image) inside the body request including more properties in the same body. In that case, I strongly recommend using the attribute [FromForm] before your object parameter in your API. Like the example below:

Beginning of API declaration in .net core

Then if you want to test your API via post-man you must use body with form-data type. For your file/image give the property name and select 'File' type on the key side, and on the value side, select the file by clicking 'Select Files', do the same for the other properties, key = property name, and value for their values (being string, double ... and so on). Like the example below:

Post-man example of HTTP POST with a file inside the body.

Related