Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API POST calls to upload a List of objects containing IFormFile

I'm using IFormFile from ASP.NET Core 2.2 to build a file upload web service call. Because I need specific data associated with every file upload, I created a custom model class to contain the data with an IFormFile property.

public class Document
{
    public string FileId { get; set; }
    public string FileTitle { get; set; }
    public string CategoryId { get; set; }

    public IFormFile Content { get; set; }
}

The below works fine when only one Document is being uploaded.

[HttpPost]
[Route("UploadDoc")]
public async Task<IActionResult> DocumentUpload ([FromForm] Document document) { }

However, I wish to accept a list of Documents to be uploaded at once. When I configure my POST to accept a list, it no longer works. I know for a fact that IList<IFormFile> works, but the issue is that I need additional data for each file.

[HttpPost]
[Route("UploadDoc")]
public async Task<IActionResult> DocumentUpload ([FromForm] IList<Document> document) { }

I am testing my API using Postman and I've included a screenshot of my form-data call. When executed, my Postman will hang. Oddly enough, when I remove the IFormFile property from my Document class, the call works. Can I make this work or is there a workaround?

Postman call

like image 345
jmak24 Avatar asked Sep 02 '25 15:09

jmak24


1 Answers

It's a known bug

As a workaround, you can wrap the IFormFile in another class and it will work

    public class Company
    {
        public IList<Person> Employees { get; set; } = new List<Person>();
    }

    public class Person
    {
        public FormFileWrapper IdImage { get; set; }
    }

    public class FormFileWrapper
    {
        public IFormFile File { get; set; }
    }

then you don have to add the index in your html

<form action="http://localhost:5000/api/Values" method="post" enctype="multipart/form-data">
    <p><input type="file" name="Employees[0].IdImage.File"></p>
    <p><input type="file" name="Employees[1].IdImage.File"></p>
    <p><button type="submit">Submit</button></p>
</form>
like image 77
Wahid Bitar Avatar answered Sep 05 '25 05:09

Wahid Bitar