I have created a Asp.net core 8 web api with Swagger to upload files to server.
The following code is working fine:
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();
}