我希望将使用 HttpPostedFileBase
上传的图像保存到数据库中。
我该怎么做?我应该如何构建数据库字段?我需要编写什么代码来将其保存到数据库中?
我希望将使用 HttpPostedFileBase
上传的图像保存到数据库中。
我该怎么做?我应该如何构建数据库字段?我需要编写什么代码来将其保存到数据库中?
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
类是数据库实体,因此您需要在数据库中包含Name
、ContentType
和Data
。 uploadedImage
是HttpPostedFileBase
。
[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);
}
}
我们在SQL数据库中使用varbinary(max)数据类型来存储图像和其他文件。
有关如何使用此数据类型的示例,请参见:http://msdn.microsoft.com/en-us/library/a1904w6t(VS.80).aspx
首先,将图像存储在数据库中是一个有争议的话题,因此请确保考虑清楚这是否真的是您想要的。有关详细讨论,请参见:
接下来要考虑的是使用什么技术。您将使用Linq2SQL、NHibernate、Entity Framework还是纯ADO.NET?选择技术时,应考虑整个应用程序架构,而不仅仅是专注于存储图像(除非这就是您的应用程序所做的全部)。一旦确定了这一点,请查看所选技术如何处理二进制数据。
您可以通过HttpPostedFileBase.InputStream
访问二进制数据。