1

I am beginner to ASP.NET MVC 4 ... I want to upload images from my form and save them into the SQL database by using Entity Framework. I have searched a lot but couldn't succeed yet,,

3
  • 2
    This will help you: stackoverflow.com/questions/19185848/… [Uplopad and Fetch image in mvc][1] [1]: stackoverflow.com/questions/19185848/… Commented Apr 8, 2014 at 11:45
  • Please include some code to show us what you've tried. Commented Apr 8, 2014 at 13:05
  • At the risk of starting a flame war, unless you have a very specific business case that requires images actually be stored in the database, refrain from doing so. Pulling an image from a database for display on the web requires spinning up the entire ASP.NET framework just to serve the image, where as a static reference to an image allows IIS to serve it directly. Also, you'll have zero ability to optimize resource handling through things like CDNs, etc. Commented Apr 8, 2014 at 13:58

1 Answer 1

3

First Convert image into bytes and then assign generated bytes of the property of you model.

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
 MemoryStream ms = new MemoryStream();
 imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
 return  ms.ToArray();
}

and then

YourModel obj = new YourModel()
obj.Image = imageToByteArray(image);
yourDbContext.YourModels.Add(obj);
yourDbContext.Savechanges()

Edited: From Byte[] to image

public Image byteArrayToImage(byte[] byteArrayIn)
{
     Image returnImage = null;
     using (MemoryStream ms = new MemoryStream(byteArrayIn))
     {
         returnImage = Image.FromStream(ms);
     }
     return returnImage;
}
Sign up to request clarification or add additional context in comments.

2 Comments

How to retrieve image after saving this?
Convert back the bytes to Image. I have edited the answer accordingly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.