作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何在 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; }
}
[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);
}
关于asp.net-mvc - MVC 4 将配置文件图像添加到 RegisterModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19776346/
如何在 MVC 4 中添加将个人资料图片上传到默认 RegisterModel 的选项? 最佳答案 此答案将图像转换为字节数组,以便您可以将其保存在数据库中。如果您想将图像保存到文件存储,可以轻松修改
我想在我的网站的注册表中添加一个界面。我们称之为 IShape。有多种接口(interface)实现,例如 ISquare 和 ICycle,除了接口(interface)中声明的共享属性之外,每个属
任何人都可以提供使用 SageMaker Pipeline 部署 pytorch 模型的示例吗? 我使用 SageMaker Studio 的 MLOps 模板(用于模型构建、训练和部署的 MLOps
我是一名优秀的程序员,十分优秀!