gpt4 book ai didi

asp.net-mvc - MVC 4 将配置文件图像添加到 RegisterModel

转载 作者:行者123 更新时间:2023-12-04 04:35:43 25 4
gpt4 key购买 nike

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

最佳答案

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

View 模型的代码。重要的部分是 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 View 的 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 模板中的注册的快速总结。

关于asp.net-mvc - MVC 4 将配置文件图像添加到 RegisterModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19776346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com