views:

75

answers:

4

I want to save images that are uploaded with httppostedfilebase into a database.

How do I do this? How do I structure the database fields? What code do I write to save it to the database?

+1  A: 
if(uploadedImage == null || uploadedImage.ContentLength == 0)
{
    // no image
}

var image = new Image();
image.Name = uploadedImage.FileName;
image.ContentType = uploadedImage.ContentType;
int length = uploadedImage.ContentLength;
byte[] buffer = new byte[length];
uploadedImage.InputStream.Read(buffer, 0, length);
image.Data = buffer;

Image class is database entity, so you need Name, ContentType and Data in your database. uploadedImage is HttpPostedFileBase.

Necros
do I need to open a Stream???
Ragims
+1  A: 

We use datatype varbinary(max) for storing images and other files in a SQL database.

For an example of how to work with this data type, see: http://msdn.microsoft.com/en-us/library/a1904w6t(VS.80).aspx

Shiraz Bhaiji
A: 

First of all, storing images in a database is a controversial subject, so make sure to consider whether this is really what you want. For an elaborate discussion see:

http://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay#3756

The next thing to consider is what technology to use. Will you be using Linq2SQL, NHibernate, Entity Framework or plain ADO.NET? When choosing technology you should take the overall application architecture into account and not just focus on storing images (unless that is all your app does). Once that is settled, check out how the chosen technology handles binary data.

You can get to the binary data through HttpPostedFileBase.InputStream.

Rune
A: 
[HttpPost]
    public ActionResult SaveImage(HttpPostedFileBase image)
    {
       Foo foo=new Foo();
       if (image != null)
            {
                foo.ImageMimeType = image.ContentType;//public string ImageMimeType { get; set; }
                foo.ImageData = new byte[image.ContentLength];//public byte[] ImageData { get; set; }
                image.InputStream.Read(product.ImageData, 0, image.ContentLength);
            }
            fooRepository.Save(foo);
        }
    }
Akyegane