简体   繁体   English

使用 asp.net mvc 4 + Entity Framework 将图像保存到数据库

[英]Saving images to database with asp.net mvc 4 + Entity Framework

I have this:我有这个:

Model:模型:

 public string Picture { get; set; }

 [Column(TypeName = "image")]
 public byte[] Image { get; set; }

 [Display(Name = "Display profile Image")]
 public bool DisplayItem { get; set; }

View:看法:

<div class="editor-label">
    @Html.LabelFor(model => model.DisplayItem)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.DisplayItem)
    @Html.ValidationMessageFor(model => model.DisplayItem)
</div>
<div class="editor-label">
    @Html.LabelFor(m => m.Image)
</div>

<input type="file" name="file"/>

And controller:和控制器:

public ActionResult Edit(string UserId)
{
        string username = User.Identity.Name;
        // Fetch the userprofile
        UserProfile user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));
        // Construct the viewmodel

        return View(user);
}

[HttpPost]
public ActionResult Edit(UserProfile userprofile, HttpPostedFileBase file)
{
        if (file != null && file.ContentLength > 0)
        {
            // extract only the fielname
            var fileName = Path.GetFileName(file.FileName);
            // store the file inside ~/App_Data/uploads folder
            var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
            file.SaveAs(path);
        }

        if (ModelState.IsValid)
        {
            string username = User.Identity.Name;
            // Get the userprofile
            UserProfile user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));

            // Update fields

            user.FirstName = userprofile.FirstName;
            user.LastName = userprofile.LastName;
            user.Email = userprofile.Email;
            user.Motto = userprofile.Motto;

            user.PlaceOfBirth = userprofile.PlaceOfBirth;
            user.HowManyBikes = userprofile.HowManyBikes;
            user.BesideYourBeth = userprofile.BesideYourBeth;
            user.NicestRide = userprofile.NicestRide;
            user.WorstRide = userprofile.WorstRide;
            user.AmountKmPerYear = userprofile.AmountKmPerYear;
            user.AverageSpeed = userprofile.AverageSpeed;
            user.AbleToChatWhileRiding = userprofile.AbleToChatWhileRiding;
            user.PhoneNumber = userprofile.PhoneNumber;

            db.Entry(user).State = EntityState.Modified;

            db.SaveChanges();

            return RedirectToAction("Edit", "Account");
        }

        return View(userprofile);
}

But I want to save the images to the database, and not to only folder.但我想将图像保存到数据库,而不仅仅是文件夹。 But how to do that in the controller action?但是如何在控制器动作中做到这一点呢? THe images are now stored in maps and not in the database图像现在存储在地图中而不是数据库中

Thank you谢谢

this is the Edit:这是编辑:

[HttpPost]
        public ActionResult Edit(UserProfile userprofile, HttpPostedFileBase file)
        {

            if (file != null && file.ContentLength > 0)
            {


                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                file.SaveAs(path);
            }



            if (ModelState.IsValid)
            {
                string username = User.Identity.Name;
                // Get the userprofile
                UserProfile user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));

                // Update fields

                user.FirstName = userprofile.FirstName;
                user.LastName = userprofile.LastName;
                user.Email = userprofile.Email;
                user.Motto = userprofile.Motto;

                user.PlaceOfBirth = userprofile.PlaceOfBirth;
                user.HowManyBikes = userprofile.HowManyBikes;
                user.BesideYourBeth = userprofile.BesideYourBeth;
                user.NicestRide = userprofile.NicestRide;
                user.WorstRide = userprofile.WorstRide;
                user.AmountKmPerYear = userprofile.AmountKmPerYear;
                user.AverageSpeed = userprofile.AverageSpeed;
                user.AbleToChatWhileRiding = userprofile.AbleToChatWhileRiding;
                user.PhoneNumber = userprofile.PhoneNumber;

                db.Entry(user).State = EntityState.Modified;

                db.SaveChanges();

                return RedirectToAction("Edit", "Account");
            }

            return View(userprofile);
        }

oke, I have it now like this:好吧,我现在是这样的:

[HttpPost]
        public ActionResult Edit(UserProfile userprofile, HttpPostedFileBase file)
        {

            if (file != null && file.ContentLength > 0)
            {               
                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                // store the file inside ~/App_Data/uploads folder

                userprofile.Image = new byte[file.ContentLength];
                file.InputStream.Read(userprofile.Image, 0, file.ContentLength);

                var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                file.SaveAs(path);
            }
        etc...

I see the images in the folder: ~/App_Data/uploads but not in the database, column: Image - NULL我看到文件夹中的图像:~/App_Data/uploads 但不在数据库中,列:Image - NULL

I have it now like this:我现在是这样的:

 [HttpPost]
        public ActionResult Edit(UserProfile userprofile, HttpPostedFileBase file)
        {

            if (file != null && file.ContentLength > 0)
            {               
                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                // store the file inside ~/App_Data/uploads folder



                var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                file.SaveAs(path);
            }



            if (ModelState.IsValid)
            {
                string username = User.Identity.Name;
                // Get the userprofile
                UserProfile user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));

                // Update fields

                user.FirstName = userprofile.FirstName;
                user.LastName = userprofile.LastName;
                user.Email = userprofile.Email;
                user.Motto = userprofile.Motto;

                user.PlaceOfBirth = userprofile.PlaceOfBirth;
                user.HowManyBikes = userprofile.HowManyBikes;
                user.BesideYourBeth = userprofile.BesideYourBeth;
                user.NicestRide = userprofile.NicestRide;
                user.WorstRide = userprofile.WorstRide;
                user.AmountKmPerYear = userprofile.AmountKmPerYear;
                user.AverageSpeed = userprofile.AverageSpeed;
                user.AbleToChatWhileRiding = userprofile.AbleToChatWhileRiding;
                user.PhoneNumber = userprofile.PhoneNumber;

                userprofile.Image = new byte[file.ContentLength];
                file.InputStream.Read(userprofile.Image, 0, file.ContentLength);

                db.Entry(user).State = EntityState.Modified;               

                db.SaveChanges();

                return RedirectToAction("Edit", "Account");
            }

            return View(userprofile);
        }

but still in database Image is NULL但仍在数据库中 Image is NULL

I'll assume that you need the image saved in the user profiles table.我假设您需要保存在用户配置文件表中的图像。

You need to add this field to the user entity :您需要将此字段添加到用户实体:

public byte[] Image { get;set; }

and set并设置

user.Image = new byte[file.ContentLength];
file.InputStream.Read(user.Image,0, file.ContentLength);

Hope this helps.希望这可以帮助。

Full Example here :完整示例在这里:

[HttpPost]
        public ActionResult Edit(UserProfile userprofile, HttpPostedFileBase file)
    {

        if (file != null && file.ContentLength > 0)
        {
            // extract only the fieldname
            var fileName = Path.GetFileName(file.FileName);
            // store the file inside ~/App_Data/uploads folder
            var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
            file.SaveAs(path);
        }

        if (ModelState.IsValid)
        {
            string username = User.Identity.Name;
            // Get the userprofile
            UserProfile user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));

            // Update fields
            user.Image = new byte[file.ContentLength];
            file.InputStream.Read(user.Image,0, file.ContentLength);

            user.FirstName = userprofile.FirstName;
            user.LastName = userprofile.LastName;
            user.Email = userprofile.Email;
            user.Motto = userprofile.Motto;

            user.PlaceOfBirth = userprofile.PlaceOfBirth;
            user.HowManyBikes = userprofile.HowManyBikes;
            user.BesideYourBeth = userprofile.BesideYourBeth;
            user.NicestRide = userprofile.NicestRide;
            user.WorstRide = userprofile.WorstRide;
            user.AmountKmPerYear = userprofile.AmountKmPerYear;
            user.AverageSpeed = userprofile.AverageSpeed;
            user.AbleToChatWhileRiding = userprofile.AbleToChatWhileRiding;
            user.PhoneNumber = userprofile.PhoneNumber;

            db.Entry(user).State = EntityState.Modified;

            db.SaveChanges();

            return RedirectToAction("Edit", "Account");
        }

        return View(userprofile);
    }

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

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