how to uploading Iformfile with other model properties in asp.net core webapi?

Viewed 5454

i am trying to post the file using IFormfile & other property models data in asp.net core web api using swagger but i am getting any way to do both the things(uploading file and other model properties) simultaneously.

please suggest me some good way to do this.

3 Answers

Inside a web api you could do as the following -

[HttpPost("Data")]
public async Task<IActionResult> postData([FromForm] UploadModal uploadModal)
{
 //getting file from client
 var postedFile = Request.Form.Files[0];

 //then set an Uploads folder
  var upload = path.Combine(Directory.GetCurrentDirectory(), "Uploads");

/*remember you have to create a new folder named "Uploads"(same as 
  above) inside your API folder, this is where all the uploads are going 
  to be stored*/

 //now check if file is empty or not
  if (postedFile.length > 0){
   
  //the below LOC is necessory for handling uploads and downloads 
   inside http requests
  var fileName = ContentDispositionHeaderValue.Parse(postedProfile.ContentDisposition).FileName;

  //specify the path to save

  var pathToSave = Path.Combine(Uploads, fileName.ToString());

  //finally create the file using new FileStream() method

  using(var fileStream = new FileStream(pathToSave, FileMode.Create)){
   await postedProfile.CopyToAsync(fileStream);
}
   }
  
  //return a status Ok with details
  return Ok($"Name = {uploadModal.Var1} and fileName = 
  {uploadModal.File}");
}else {
   return BadRequest(new ProblemDetails{Detail = "Failed to 
   Upload"});
 }

on doing this your server could give a 500 response, as the [FormForm] attribute is not mapped. TO avoid this do -

public class UploadModel{

    public string Var1 { get; set; }
     
    [NotMapped]
    public IFormFile File { get; set; }

}

hope that would work for you. I would suggest another solution as well , once I get.

Related