How to store Picture User Profile on Database Table AspNetUsers using mvc asp.net core 5?

ahmed salah 3,216 Reputation points
2022-12-03T10:37:12.17+00:00

I working on asp.net core 5 mvc web application , I face issue I can't store Picture User on database table [dbo].[AspNetUsers].

so can you tell me how to store personal picture of user on table [dbo].[AspNetUsers].

I already add new column PictureUser on table [dbo].[AspNetUsers] to store User Picture .

I need to know what I will modify on controller and view to store user picture on database table .

I working on Microsoft identity membership when register user

my model as

public class RegisterVM  
{  
    public string EmailAddress { get; set; }  
    public string Password { get; set; }  
    public byte[] PictureUser { get; set; }  
  
}  

my action controller

[HttpPost]

 public async Task<IActionResult> Register(RegisterVM registerVM)  
    {  
         
        var newUser = new ApplicationUser()  
        {  
            FullName = registerVM.FullName,  
            Email = registerVM.EmailAddress,  
            UserName = registerVM.EmailAddress,  
            //How to add Image upload Here  
        };  
      
        var newUserResponse = await _userManager.CreateAsync(newUser, registerVM.Password);  
        if (newUserResponse.Succeeded)  
        {  
            await _signInManager.SignInAsync(newUser, isPersistent: false);  
        
            return View("RegisterCompleted");  
        }  
         
        return View(registerVM);   
    }  

on view

@model RegisterVM;  
  
  
          
                <form asp-action="Register">  
                    <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
  
                      
                    <div class="form-group">  
                        <label asp-for="EmailAddress" class="control-label"></label>  
                        <input asp-for="EmailAddress" class="form-control" />  
                        <span asp-validation-for="EmailAddress" class="text-danger"></span>  
                    </div>  
                    <div class="form-group">  
                        <label asp-for="Password" class="control-label"></label>  
                        <input asp-for="Password" class="form-control" />  
                        <span asp-validation-for="Password" class="text-danger"></span>  
                    </div>  
                     //How to add Image upload Here  
  
                    <div class="form-group">  
                        <input class="btn btn-outline-success float-right" type="submit" value="Sign up" />  
                         
                    </div>  
                </form>  

How to add Image Upload on View And Controller Action this is Exactly my Question ?

Developer technologies ASP.NET ASP.NET Core
Developer technologies ASP.NET Other
{count} votes

Accepted answer
  1. Anonymous
    2022-12-05T05:34:48.597+00:00

    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:

    1. 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.  
      }  
      
    2. 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.  
      }  
      
    3. 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)  
          {  
          }  
      }  
      
    4. 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();  
          }  
      }  
      
    5. In the Register.cshtml page, use an input file element to upload file: 266960-image.png
      Then, the output as below:

    266985-image1.gif


    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

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.