Mejan
Mejan

Reputation: 1276

How to upload a profile picture and update it in identity asp.net core 3

I want to upload a profile picture in the identity user and update it in account management. if there is any post with good examples for asp.net core please give me links.

Upvotes: 3

Views: 7003

Answers (1)

Mejan
Mejan

Reputation: 1276

I did it myself with FileForm Method. First You Have to Add string property in User Class(https://learn.microsoft.com/en-us/aspnet/core/security/authentication/add-user-data?view=aspnetcore-3.0&tabs=visual-studio).

        public string Avatar { get; set; }

and then, update the Manage/Index files by following the documentation. Now, How to create the file upload system? I did like the code below. but if i need to change something for security, please don't forget to help.

                    if (Input.Avatar != null)
                {
                    string existfile = Path.Combine(hostingEnvironment.WebRootPath, "uploads", user.Avatar);
                    System.IO.File.Delete(existfile);

                }
                var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads", "avatar");
                var filePath = Path.Combine(uploads, fileName);
                this.Image.CopyTo(new FileStream(filePath, FileMode.Create));
                user.Avatar = fileName; // Set the file name

GetUniqueFileName Class after the PostAsync class:

        private string GetUniqueName(string fileName)
    {
        fileName = Path.GetFileName(fileName);
        return Path.GetFileNameWithoutExtension(fileName)
               + "_" + Guid.NewGuid().ToString().Substring(0, 4)
               + Path.GetExtension(fileName);
    }

You also have to add the IWebHostEnvironment dependency injection and update the cshtml form with multipart/form-data enctype. Don't forget to follow the .net documentation rules also. Good Luck!

Upvotes: 0

Related Questions