Hi @ahmed salah ,
How to store Picture User Profile on Database Table AspNetUsers using mvc asp.net core 5?
To upload file in asp.net core application, we need to use the IFormFile.
So, you can modify your code as below:
- For the RegisterVM model, change the PictureUser's data type from byte array to IFormFile.
public class RegisterVM { public string FullName { get; set; } public string EmailAddress { get; set; } public string Password { get; set; } public IFormFile PictureUser { get; set; } //use this property to upload file. }
- In the ApplicationUser class, I assume you will add custom property to the Identity User table via the ApplicationUser class. Here we need to use a byte array property to store the image data into the database.
public class ApplicationUser:IdentityUser { public int Age { get; set; } public byte[]? PictureSource { get; set; } //use this property to store the image srouce into database. }
- Enable migration and update the database. After that you can find the PictureSource column in the AspNetUsers table.
public class ApplicationDbContext : IdentityDbContext { public DbSet<ApplicationUser> ApplicationUsers { get; set; } public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } }
- In the Account Register Post method, copy the IFormFile to a stream and save it as a byte array in the database.
public class AccountController : Controller { private readonly UserManager<ApplicationUser> _userManager; public AccountController(UserManager<ApplicationUser> userManager) { _userManager= userManager; } public IActionResult Register() { return View(); } [HttpPost] public async Task<IActionResult> Register(RegisterVM registerVM) { if (ModelState.IsValid) { var newUser = new ApplicationUser() { Email = registerVM.EmailAddress, UserName = registerVM.EmailAddress, }; if (registerVM.PictureUser.Length>0) { using (var memoryStream = new MemoryStream()) { await registerVM.PictureUser.CopyToAsync(memoryStream); // Upload the file if less than 2 MB if (memoryStream.Length < 2097152) { newUser.PictureSource = memoryStream.ToArray(); } else { ModelState.AddModelError("File", "The file is too large."); } } } var result = await _userManager.CreateAsync(newUser); if (result.Succeeded) { //... return RedirectToAction("Index", "Home"); } } return View(); } }
- In the Register.cshtml page, use an input file element to upload file:
Then, the output as below:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion