【问题标题】:How to upload a profile picture and update it in identity asp.net core 3如何上传个人资料图片并在身份 asp.net core 3 中更新
【发布时间】:2020-03-05 13:39:32
【问题描述】:

我想上传identity 用户的头像并在账户管理中更新。如果有任何关于 asp.net core 的好例子的帖子,请给我链接。

【问题讨论】:

    标签: identity razor-pages asp.net-core-3.0 avatar profile-picture


    【解决方案1】:

    我自己用 FileForm 方法做的。首先你必须在用户类(https://docs.microsoft.com/en-us/aspnet/core/security/authentication/add-user-data?view=aspnetcore-3.0&tabs=visual-studio)中添加字符串属性。

            public string Avatar { get; set; }
    

    然后,按照文档更新管理/索引文件。现在,如何创建文件上传系统?我确实喜欢下面的代码。但如果我需要更改某些内容以确保安全,请不要忘记提供帮助。

                        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
    

    PostAsync 类之后的GetUniqueFileName 类:

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

    您还必须添加 IWebHostEnvironment 依赖注入并使用 multipart/form-data enctype 更新 cshtml 表单。也不要忘记遵守 .net 文档规则。祝你好运!

    【讨论】:

    • 我更喜欢使用bool 之类的HasPhoto 来了解用户是否有图像,并使用用户ID(Guid)作为文件名。在我的图像上传和调整大小方法中,我将所有图像转换为 jpg,因此我也不必保存扩展名。然后在表单上,​​用户可以选中或取消选中HasPhoto。如果未选中,则删除照片。
    猜你喜欢
    • 2012-05-01
    • 2020-01-10
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    • 2018-06-06
    • 2022-11-16
    • 2015-05-22
    • 1970-01-01
    相关资源
    最近更新 更多