ASP.NET MVC代码优先认证页面,无法上传文件

问题描述 投票:0回答:1

我创建了一个带有身份验证的 ASP.NET MVC 项目,我想添加一个新字段来注册页面以上传用户图像。问题是当我保存新帐户时,图像列是空的。

经过一番挖掘,我发现文件没有从视图传输到模型(

model.Image
始终为空)。

这些是我已完成的步骤:

  1. 我更新了身份

    Models.cs
    并添加了

    public byte[] Image { get; set; }
    
  2. 我使用新列(类型为

    varbinary(max)
    )更新了数据库

  3. AccountViewModels
    ,我创造了

    [Display(Name = "Image")]
    public HttpPostedFileBase Image { get; set; }
    
  4. Register.cshtml
    中我插入:

    @Html.LabelFor(m => m.Fotografie, new { @class = "col-md-2 col-form-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(model => model.Image, new { @class = "form-control", type = "file", name = "Image" })
    </div>
    
  5. AccountController
    中,我写了以下代码

    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        byte[] data;
    
        if (model.Fotografie != null)
        {
            using (Stream inputStream = model.Fotografie.InputStream)
            {
                MemoryStream memoryStream = inputStream as MemoryStream;
    
                if (memoryStream == null)
                {
                    memoryStream = new MemoryStream();
                    inputStream.CopyTo(memoryStream);
                }
    
                data = memoryStream.ToArray();
            }
        }
        else 
            data = null;
    
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser 
                       {
                           UserName = model.Email,
                           Email = model.Email,
                           Image = data, 
                       };
        }
    }
    

我在 StackOverflow 和 Google 上尝试了每种组合,并得出结论:

  1. 我不明白数据是如何传输的或者
  2. 我错过了一些东西
c# sql asp.net asp.net-mvc entity-framework
1个回答
0
投票

在表单标签中设置

enctype="multipart/form-data"
,如 @VDWWD 建议,并从 AccountViewModels 中删除 HttpPosted... 属性,您必须将模型与图像文件数据分开:

[HttpPost]
public async Task<ActionResult> Register(RegisterViewModel model, HttpPostedFileBase Image)
{
    byte[] data;

    if (Image != null && Image.ContentLength > 0)
    {
        using (Stream inputStream = Image.InputStream)
        {
            MemoryStream memoryStream = inputStream as MemoryStream;

            if (memoryStream == null)
            {
                memoryStream = new MemoryStream();
                inputStream.CopyTo(memoryStream);
            }

            data = memoryStream.ToArray();
        }
    }
    else 
        data = null;

    if (ModelState.IsValid)
    {
        var user = new ApplicationUser 
                   {
                       UserName = model.Email,
                       Email = model.Email,
                       Image = data, 
                   };
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.