I have created a Asp.net core 3.1 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
version 5.6.3 in ASP.NET Core 3.1:
[HttpPost]
public ActionResult PostFile([FromForm]FileUploadRequest model)
{
}
Result: