Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save an image in a SQL Server Database?

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?

like image 222
r.r Avatar asked Mar 21 '26 10:03

r.r


2 Answers

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:

Storing Images in DB - Yea or Nay?

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.

like image 65
Rune Avatar answered Mar 22 '26 23:03

Rune


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.

like image 34
Necros Avatar answered Mar 22 '26 22:03

Necros



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!