It works 100%. Tested. Please do the below steps:
You should create a custom class for the model as
public class FileInputModel
{
public string Name { get; set; }
public IFormFile FileToUpload { get; set; }
}
and the form like
<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="UploadFileViaModel" >
<input name="Name" class="form-control" />
<input name="FileToUpload" type="file" class="form-control" />
<input type="submit" value="Create" class="btn btn-default" />
</form>
and the controller method like
[HttpPost]
public async Task<IActionResult> UploadFileViaModel([FromForm] FileInputModel model)
{
if (model == null || model.FileToUpload == null || model.FileToUpload.Length == 0)
return Content("file not selected");
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", model.FileToUpload.FileName);
using (var stream = new FileStream(path, FileMode.Create))
{
await model.FileToUpload.CopyToAsync(stream);
}
return RedirectToAction("Files");
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…