I did a quick Google Search:
c# mvc form file example - Google Search[
^]
Found this accepted solution:
MVC: How to post File Upload and other form fields to one action [solved] - StackOverflow[
^]
UPDATE
I have put together a sample app to check my updated solution. Here is the working solution for attaching an image that is based off this:
Upload files in ASP.NET Core | Microsoft Learn[
^].
NOTE: I have not implemented the saving of the image/file, I have left that for you.
1. Form Data Model:
public class DataModel
{
public string Name { get; set; }
public string Email { get; set; }
public IFormFile? FormFile { get; set; }
}
2. Page:
@model DataModel
@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary();
<fieldset>
@Html.EditorFor(model => model.Name)
</fieldset>
<fieldset>
@Html.EditorFor(model => model.Email)
</fieldset>
<fieldset>
<input type="file" asp-for="FormFile" type="file"/>
</fieldset>
<input type="submit" id="btnSubmit" value="Upload" />
}
3. Controller
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
=> _logger = logger;
public IActionResult Index()
=> View();
[ResponseCache(Duration = 0,
Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
=> View(new ErrorViewModel
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
});
[HttpPost]
public async Task<IActionResult> FileUpload(DataModel model)
{
if (ModelState.IsValid)
{
if (model.FormFile == null)
{
ModelState.AddModelError("File", "Please Upload Your file");
}
else if (model.FormFile.Length > 0)
{
int MaxContentLength = 1024 * 1024 * 3;
string[] AllowedFileExtensions =
{
".jpg", ".gif", ".png", ".pdf"
};
if (!AllowedFileExtensions.Contains(
model.FormFile.FileName.Substring(
model.FormFile.FileName.LastIndexOf('.'))))
{
ModelState.AddModelError("File",
"Please file of type: " +
string.Join(", ", AllowedFileExtensions));
}
else if (model.FormFile.Length > MaxContentLength)
{
ModelState.AddModelError("File",
"Your file is too large, maximum allowed size is: " +
MaxContentLength + " MB");
}
else
{
using var memoryStream = new MemoryStream();
await model.FormFile.CopyToAsync(memoryStream);
if (memoryStream.Length < MaxContentLength)
{
Debugger.Break();
}
else
{
ModelState.AddModelError("File", "The file is too large.");
}
}
}
return Ok();
}
return BadRequest();
}
}
Set a breakpoint on the first line in the
FileUpload
. When the breakpoint is hit, inspect the
model
and you will see the reference to the file data. I have set a
Debugger.Break();
where you need to handle the saving of the file stream.
Enjoy!
BONUS
In building my solution, I came across this page with client-side file validation:
How to upload a file in ASP.MVC[
^]. Ignore the rest, just look at the javascript, this script might be of interest to you.