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 wr开发者_高级运维ite to save it to the database?
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
.
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
.
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
[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);
}
}
精彩评论