This is my following attempt. I am unable to upload pic in database using ASP.net Core 6. Controller.cs
[HttpPost]
public IActionResult Create(TbUser tbUser, UserRoleViewModel model)
{
if (ModelState.IsValid)
{
var selectedRole = model.RoleId;
//string stringFileName = UploadFile(model);
string wwrootpath = _webHostEnvironment.WebRootPath;
string filename = Path.GetFileNameWithoutExtension(model.fileName.FileName);
string filenameWithExt = Path.GetExtension(model.fileName.FileName);
filename = filename + DateTime.Now.ToString("yymmssfff") + filenameWithExt;
model.fileName = filename;
string path = Path.Combine(wwrootpath + "uploadfiles", filename);
using (var filestream = new FileStream(path, FileMode.Create))
{
model.fileName.CopyTo(filestream);
}
_context.TbUsers.Add(tbUser);
_context.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
ViewModel.cs
public string? UserPicture { get; set; }
public IFormFile? fileName { get; set; }
model.cs
public string? UserPicture { get; set; }
html.cstml
<form asp-action="Create" method="post" >
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="UserPicture" class="control-label"></label>
<input asp-for="UserPicture" class="form-control" type="file" />
<span asp-validation-for="UserPicture" class="text-danger"></span>
</div>
</form>
Error: Cannot implicitly convert type string to Microsoft.AspNetCore.Http.IFormFile @
model.fileName = filename;
database Entity: User_Picture => varchar(50)
Your codes indicates you were tring to copy the tempfile to wwwroot,if you just want to update the file to db and show the pic from db,you could create another endpoint that return the file content and try as below:
public async Task<IActionResult> Upload(ViewModel viewModel)
{
............
using (var memoryStream = new MemoryStream())
{
await viewModel.file.CopyToAsync(memoryStream);
// check the size of the file
if (memoryStream.Length < 2097152)
{
var file = new AppFile()
{
Id = someid,
Content = memoryStream.ToArray()
};
_context.AppFile.Add(file);
await _context.SaveChangesAsync();
var viewmodel = new ViewModel() { UserPicture = "/Home/FileEndpoint?id=" + file.Id.ToString() };
return View(viewmodel);
}
else
{
ModelState.AddModelError("File", "The file is too large.");
}
}
return BadRequest();
}
public FileResult FileEndpoint(int Id)
{
var content=_context.AppFile.FirstOrDefault (x=>x.Id == Id).Content;
return File(content, "image/png");
}
Models:
public class AppFile
{
public int Id { get; set; }
public byte[] Content { get; set; }
}
public class ViewModel
{
public string? UserPicture { get; set; }
public IFormFile file { get; set; }
}
Upload View:
@model ViewModel
<form action="Upload" enctype="multipart/form-data" method="post">
<img src=@(Model.UserPicture==null?null:Model.UserPicture) />
<input asp-for="file" type="file" >
<input type="submit" value="Upload" />
</form>
The result:
You could check the document related