MVC 4将配置文件图像添加到RegisterModel

时间:2013-11-04 20:18:13

标签: asp.net-mvc asp.net-mvc-4 asp.net-membership

如何添加将配置文件图像上传到MVC 4中的默认RegisterModel的选项?

1 个答案:

答案 0 :(得分:3)

此答案将图像转换为字节数组,以便您可以将其保存在数据库中。如果要将图像保存到文件存储,可以很容易地修改它。

View Model的代码。重要的部分是multipart / form-data属性:

 @using (Html.BeginForm("Register", "Account", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary()

        <fieldset>
            <legend>Registration Form</legend>
            <ol>
                <li>
                    @Html.LabelFor(m => m.UserName)
                    @Html.TextBoxFor(m => m.UserName)
                </li>
                <li>
                    @Html.LabelFor(m => m.Password)
                    @Html.PasswordFor(m => m.Password)
                </li>
                <li>
                    @Html.LabelFor(m => m.ConfirmPassword)
                    @Html.PasswordFor(m => m.ConfirmPassword)
                </li>
                <li>
                    <label for="register-avatar">Upload your photo</label>
                    <input id="register-avatar"  type="file" name="ProfileImage" />
                </li>
            </ol>
            <input type="submit" value="Register" />
        </fieldset>
    }

RegisterModel:

public class RegisterModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    public HttpPostedFileBase ProfileImage { get; set; }

}

Register.cshtml视图的AccountController的HTTPPost:

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {

        if (ModelState.IsValid)
        {
            // Attempt to register the user
            try
            {
                WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                WebSecurity.Login(model.UserName, model.Password);

                MemoryStream target = new MemoryStream();
                model.ProfileImage.InputStream.CopyTo(target);
                byte[] data = target.ToArray();

                var profileImage = new ProfileImage();
                profileImage.Data = data;
                profileImage.MimeType = model.ProfileImage.ContentType;

                /// other code to save the image to the database

                return RedirectToAction("Index", "Profile/" + model.UserName);
            }
            catch (MembershipCreateUserException e)
            {
                ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
            }
        }

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

这是我如何设法上传配置文件图像以及内置到MVC 4模板中的注册的快速向下。