Beginer Programer
Beginer Programer

Reputation: 39

MVC 4 Asp.net ,using File Upload code How to save images in Database

here is my view

     @using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <table> 
    <tr>

<td>File :</td>    
    <td><input type="file" name="File" id="file" /> </td>
  </tr>
  <tr> 
  <td><input type="submit" name="submit" value="upload" /></td>
  </tr>

Here is my Controller

public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(Picture picture)
        {
            if (picture.File.ContentLength > 0)
            {
                var fileName = Path.GetFileName(picture.File.FileName);
                var path = Path.Combine(Server.MapPath("~/Content/Images"), fileName);
                picture.File.SaveAs(path);
            }
            return RedirectToAction("Index");
        }


and Model:

namespace FileUpload.Models
{
    public class Picture
    {
        public HttpPostedFileBase File { get; set; }



    }

This code helps me to save image in my MVC project root Image folder , but I want to save it to my database . I have tried many tutorial but could not succeed yet ... ' I am Actually making the student form every student will register his picture.

Upvotes: 0

Views: 2440

Answers (1)

Nilesh Gajare
Nilesh Gajare

Reputation: 6398

Convert your image into bytes and then store it in your database

[HttpPost]
        public ActionResult Index(Picture picture)
        {
            byte[] Image;
            if (Request.Files["files"] != null)
            {
               using (var binaryReader = new BinaryReader(Request.Files["file"].InputStream))
                {
                   Image = binaryReader.ReadBytes(Request.Files["files"].ContentLength);
                }
               Picture.File =Image;
            }
            return RedirectToAction("Index");
        }

Model

public class Picture
    {
        public byte[] File { get; set; }
    }

View For Displaying Image

if (Model.File != null)
  {
     string imageBase64 = Convert.ToBase64String(Model.File );
     string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
     <img src="@imageSrc" width="100" height="100" />
  }

Upvotes: 1

Related Questions