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

偶尔善良 提交于 2021-02-06 13:22:49

问题


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

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


回答1:


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);
    }


来源:https://stackoverflow.com/questions/26347705/saving-images-to-database-with-asp-net-mvc-4-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!