Tuesday, 25 February 2025

How to get a upload button in swagger for IFormFile combined with other properties?

I have created a Asp.net core 8 web api with Swagger to upload files to server.

The following code is working fine:

    [HttpPost("PostFile")]
    public ActionResult PostFile(IFormFile uploadedFile)
    {            
        var saveFilePath = Path.Combine("c:\\savefilepath\\", uploadedFile.FileName);
        using (var stream = new FileStream(saveFilePath, FileMode.Create))
        {
            uploadedFile.CopyToAsync(stream);
        }
        return Ok();
    }

I get a nice upload button in swagger when I try to run this.


However, now I wanted to use a different model. that has some more properties along with the IFormFile.

public class FileUploadRequest
{
    public string UploaderName { get; set; }
    public string UploaderAddress { get; set; }
    public IFormFile File { get; set; }
}

When I try to use this model, I dont see any upload button in Swagger that will help me to attach the file in the request.




For some reason, it shows the IFormFile as String. How can I get a upload button here?

In ASP.NET Core Web API, it binds application/json format data by default. But what your model need is multipart/form-data type data. So you need [FromForm] attribute to specific the source.

I use Swashbuckle.AspNetCore  in ASP.NET Core 8:

[HttpPost]
public ActionResult PostFile([FromForm]FileUploadRequest model)
{

}


You can use IFormFile again in [HttpPost] so you can see the button.

    public class FileUploadRequest
        {
            public string? UploaderName { get; set; }
            public string? UploaderAddress { get; set; }
            public IFormFile? File { get; set; }
        }

        [HttpPost]
        public IActionResult PostFile(IFormFile file, FileUploadRequest model)
        {
           
                var saveFilePath = Path.Combine("c:\\savefilepath\\", model.UploaderAddress!);
                using (var stream = new FileStream(saveFilePath, FileMode.Create))
                {
                  file.CopyToAsync(stream);
                }
                return Ok();
            }