繁体   English   中英

如何在asp.net mvc中使用用户对象将图像传递到数据库

[英]how to pass image to database with user object in asp.net mvc

模型是用户:

 public class Users
    {
        [Key]
        public int UserId { get; set; }
        [Required]
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        [Required]
        public string Username { get; set; }
        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
        public string UserImage { get; set; }
    }

在用户控制器中创建ActionMethod:

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "UserId,Firstname,Lastname,Username,Password,UserImage")] Users users)
        {
            if (ModelState.IsValid)
            {
                db.Users.Add(users);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(users);
        }

最后,Create视图如下所示:

@model WebApplication2.Models.Users

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Users</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Firstname, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Firstname, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Firstname, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Lastname, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Lastname, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Lastname, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Username, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.UserImage, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <input type="file" name="UserImage" value="" />
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

所以请帮助我,我该怎么做?我尝试了很多但失败了的用户对象,将图像名称传递给数据库。

不要使用EF中的实体类在视图和操作方法之间传输数据。 您应该创建一个视图模型。 您可以为HttpPostedFileBase类型的UserImage添加一个属性。

public class CreateUserVm
{       
    public int UserId { get; set; }
    [Required]
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    [Required]
    public string Username { get; set; }
    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    public HttpPostedFileBase UserImage { get; set; }
}

现在,在GET中,确保发送此CreateUserVm类的对象。

public ActionResult Create()
{
  return View(new CreateUserVm());
}

并且您的创建视图将强类型于该视图模型。

@model YourNameSpaceHere.CreateUserVm
@using (Html.BeginForm("Create", "Home", FormMethod.Post, 
                                 new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(false)
    <div class="form-group">
        @Html.LabelFor(model => model.Name,  new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.Name, new  { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Name, 
                                      "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserImage, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
          <input type="file" name="UserImage" />
        </div>
    </div>
    <input type="submit" />
}

并且在HttpPost操作中,该操作接受我们的CreateUserVm视图模型的对象作为参数。 您可以使用唯一的名称将文件保存在磁盘中,并将其与用户记录相关联,以供以后检索。

[HttpPost]
public ActionResult Create(CreateUserVm model)
{
  if(ModelState.IsValid)
  { 
     // Posted file is available at model.UserImage property. You may save it to somewhere.
     // Quick Example of saving to disk
      var fName= Path.GetFileName(model.UserImage.FileName);
      fName = fName.Replace(" ", "_");
      fName = Guid.NewGuid().ToString()+fName;

      model.UserImage.SaveAs("~/"+fName);

      var u = new Users { Firstname = model.FirstName, Lastname=model.LastName };
      u.Password=model.Password;
      u.UserImage= fName;
      db.Users.Add(u);
      db.SaveChanges();

      return RedirectToAction("Index");       
  }
  return View(model);
}

好的,您需要做一些事情来完成这项工作。 首先,您需要在视图中更改表单类型,以向服务器指示文件即将发送:

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    //Form Stuff here
}

然后,在控制器端,您需要通过添加类型HttpPostedFileBase类型的UserImage来告诉服务器期望发布请求中的文件:

public ActionResul Upload([Bind(Include = "UserId,Firstname,Lastname,Username,Password")] Users users, HttpPostedFileBase UserImage)
{
    //Controller Logic
}

现在,您的视图正在发送图像,而控制器正在接受图像...现在,我们需要解决在数据库中存储图像的概念。 您可以通过将上载的图像(现在存储在UserImage变量中)转换为字节数组(此过程未在我的文章中显示, 但在此处进行了描述 ),然后将Users模型中的属性更改为:

public string UserImage { get; set; }

到以下内容:

public byte[] UserImage { get; set; }

但是,出于某些原因,我建议您不要这样做...相反,我建议您执行以下操作:

  1. 使用唯一名称将图像保存在服务器上的文件夹中(例如\\ App_Data \\ UserProfilePhotos \\ Bob_Smith_Profile_Photo.jpg)
  2. 将照片名称保存为数据库的UserImage属性中的字符串
  3. 在用户控制器(例如yoursite.com/Users/ProfileImage/{UserID} )中创建一个端点(操作方法),以检索图像
  4. 在您的用户个人资料视图(或显示图像的任何位置)中,动态创建一个图像标签,例如<img src="/Users/ProfileImages/1"> User Image</img> ,它将加载正确的用户图像。

我不会为您概述上述工作流程的每个步骤,但是通常这就是您描述的用例的处理方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM