Alvin Quezon
Alvin Quezon

Reputation: 1201

ASP.NET Core Upload Multiple File Web API model

I want to upload multiple files and used IFormFile to upload file using asp.net core 5 but the problem is it shows me string data type instead of the IFormFile. Can I just override the field attachment: "string" property to File object? See details below:

Sample json data

id: 1122,
name: "yourname",
address: "your complete address",
attachments: [{
  "Id": 0,
  "Name": "string",
  "attachment": "string" // file attachment, I expect to be form upload button or similar
}] // please do note that this will have maximum of 5 arrays
// can attachment: string json property can be override with File object?

Main Model

public class MainModel
{
    [Required]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    [MaxLength(10)]
    public List<Attachment> Attachments { get; set; }
}

Attachment Model

public class Attachment
{
   [Required]
   public int Id { get; set; }
   [Required]
   public string Name { get; set; }
   [Required]
   [DataType(DataType.Upload)]
   public IFormFile Attachment { get; set; } // this is weird, instead of upload file it shows string instead.
}

Main Controller

[HttpPut("main/update")]
public IActionResult UpdateMain([FromForm] MainModel model)
{
   if(ModelState.IsValid)
   {
      var result = _test.UpdateMain(model);
      return Ok(new { data = result });
   }
   return BadRequest();
}

I don't know why it has a string DataType into and it doesn't make sense for me.

enter image description here

The data being sent to the web api is a File object which it doesn't make sense. Can someone help out in this one?

Upvotes: 2

Views: 9161

Answers (2)

mohammadAli
mohammadAli

Reputation: 445

The following works for in net 6 for me, instead of model we can get files from HttpContext too:

    [HttpPost("Upload")]
    public ActionResult Upload()
    {
        var files = HttpContext.Request.Form.Files;
        if (files != null && files.Count > 0)
        {
            //processing / upload
        }
        return Ok();
    }

Upvotes: 0

osman Rahimi
osman Rahimi

Reputation: 1497

Use IList<IFormFile> in your attachment. So your model would be like this:

public class MainModel
{
    [Required]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public IList<IFormFile> Attachments { get; set; }
}

In this way Attachments property contains all the selected files in your client you have chosen. Over each item of Attachments you have its FileName and some other useful data like FileSize, ...

Upvotes: 5

Related Questions