0

Im trying to let a user upload a profile picture as a part of their personal profile. The picture in this post shows the code on how I save it as byte in my database. The issue now is to show it on my page. I belive I have to convert it from byte to an image, but I don't know how or if this is the right way. Can anyone help me, or is there an easier way to handle picture upload? Thanks.

    // GET: /Manage/ChangePic
    [HttpGet]
    [AllowAnonymous]
    public async Task<IActionResult> ChangePic()
    {
        var user = await GetCurrentUserAsync();
        var model = new IndexViewModel();

        model.ProfilePic64 = Convert.ToBase64String(user.ProfilePic);

        return View(model);
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> ChangePic(IndexViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = await _userManager.FindByIdAsync(User.GetUserId());

            var breader = new BinaryReader(model.ProfilePic.OpenReadStream());

            var byteImage = breader.ReadBytes((int)breader.BaseStream.Length);

            user.ProfilePic = byteImage;

            var result = await _userManager.UpdateAsync(user);
            if (result.Succeeded)
            {
                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                // Send an email with this link
                //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                //    "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
                await _signInManager.SignInAsync(user, isPersistent: false);
                _logger.LogInformation(3, "Profile info updated");
                return RedirectToAction(nameof(ManageController.Index), "Manage");
            }
            AddErrors(result);

        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

1 Answers1

0

You need separate controller method which will return image by record ID. Here is some solution: Display image from database in asp mvc

Community
  • 1
  • 1
Mardok
  • 396
  • 4
  • 14