2

如何在 MVC 4 中添加将个人资料图片上传到默认 RegisterModel 的选项?

4

1 回答 1

3

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

视图模型的代码。重要的部分是 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>
    }

注册模型:

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 模板中的注册的简要说明。

于 2013-11-04T20:18:13.220 回答