I'm having trouble ironing out the file/image upload in ASP.NET MVC 6. Most tutorials appear to be outdated, and even some of the new ones seem to reference things that don't make sense.
In my view:
<div class="form-group">
@using (Html.BeginForm("Create", "PostNin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<label asp-for="NinImageString" class="control-label"></label>
<input type="file" name="files" class="form-control" />
}
@*<input asp-for="NinImageString" class="form-control" />
<span asp-validation-for="NinImageString" class="text-danger"></span>*@
</div>
<div class="form-group">
<label asp-for="NinImageCaption" class="control-label"></label>
<input asp-for="NinImageCaption" class="form-control" />
<span asp-validation-for="NinImageCaption" class="text-danger"></span>
</div>
And then in my controller:
// GET: PostNins/Create
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,NinFk,NinDigit,NinImageString,NinImageCaption,NinNote")] PostNin postNin, IFormFile files)
{
// need code here
if (ModelState.IsValid)
{
_context.Add(postNin);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(postNin);
}
My understanding is that I have to use IFormFile
to pull this off.
I would like to upload an image with a caption, and store it into the application folder NinImages
where I can access it later. I suppose I have questions about that too, but that's for another question.
My understanding is that I have to somehow save a copy of the image into the directory system, under wwwroot, then save the path of the file as a string to the database.
SOLUTION:
My new controller looks like below. As a note, the fileTime is only to assign a unique value to each upload, to avoid duplicates. This works in this case because only one file can be uploaded at a time.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,NinFk,NinDigit,NinImageString,NinImageCaption,NinNote")] PostNin postNin, IFormFile uploadFile)
{
if (uploadFile != null && uploadFile.Length > 0)
{
var fileTime = DateTime.UtcNow.ToString("yyMMddHHmmss");
var fileName = fileTime + Path.GetFileName(uploadFile.FileName);
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/NinFileUploads", fileName);
postNin.NinImageString = filePath;
_context.PostNins.Add(postNin);
_context.SaveChanges();
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await uploadFile.CopyToAsync(fileStream);
}
//if (ModelState.IsValid)
//{
// _context.Add(postNin);
// await _context.SaveChangesAsync();
// return RedirectToAction(nameof(Index));
//}
return RedirectToAction(nameof(Index));
}
return View(postNin);