Anand
Anand

Reputation: 93

In Asp.net (c#) ,how to store an image in database(linq to sql)?

i need to get an image from client and displayed(preview) before saving it into database..and then should be saved in database after getting preview..? Is is possible in Asp.net using c#... ?

Upvotes: 1

Views: 2236

Answers (1)

Mikael Svenson
Mikael Svenson

Reputation: 39695

Yes, it's possible.

If you are using MS SQL Server, declare a field in your table as type "image" or "varbinary". Varbinary limits the number of bytes stored depending on your version of SQL Server, so "image" is the way to go. After all, you are storing an image ;)

Then store your image as a byte array in that field.

Without seeing some code, it's hard to give code samples. Are you using SqlCommand directly, Linq2Sql, Entity framework or NHibernate to communicate with your database?

[Edit: Linq2Sql sample]

On your linq object you will have a propery called Image, if that's what you named your image/varbinary column. To assign it do this:

// assign data
byte[] imageByteArray = ...some byte data...;
myObject.Image = new Binary(imageByteArray);
// save to db
dataContext.YourTable.InsertOnSubmit(myObject); //YourTable is the name of your actual table class
dataContext.SubmitChanges();

where imageByteArray is a byte[] holding your image.

The Binary object is a wrapper around a byte[].

Upvotes: 3

Related Questions