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.
Asked
Active
Viewed 6,011 times
3

Mejan
- 918
- 13
- 18
1 Answers
0
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!

Mejan
- 918
- 13
- 18
-
I prefer to use a `bool` like `HasPhoto` to know if the user has an image or not, and use the user id (Guid) as the file name. In my image upload-and-resize-method, I convert all images to jpg, so I don't have to save the extension either. And then on the form, the user can check or uncheck `HasPhoto`. If unchecked, then delete the photo. – Stian Jun 20 '20 at 22:44