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