3

我想将上传的图像保存httppostedfilebase到数据库中。

我该怎么做呢?如何构建数据库字段?我要编写什么代码将其保存到数据库中?

4

4 回答 4

1
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;

Imageclass 是数据库实体,因此您需要Name,ContentType并且Data在您的数据库中。uploadedImageHttpPostedFileBase

于 2010-08-25T14:25:06.550 回答
1

我们使用数据类型 varbinary(max) 将图像和其他文件存储在 SQL 数据库中。

有关如何使用此数据类型的示例,请参阅:http: //msdn.microsoft.com/en-us/library/a1904w6t (VS.80).aspx

于 2010-08-25T14:28:50.847 回答
1

首先,将图像存储在数据库中是一个有争议的主题,因此请务必考虑这是否真的是您想要的。有关详细讨论,请参阅:

在 DB 中存储图像 - 是还是不是?

接下来要考虑的是使用什么技术。你会使用 Linq2SQL、NHibernate、Entity Framework 还是普通的 ADO.NET?在选择技术时,您应该考虑整个应用程序架构,而不仅仅是专注于存储图像(除非这是您的应用程序所做的全部)。确定后,查看所选技术如何处理二进制数据。

您可以通过HttpPostedFileBase.InputStream.

于 2010-08-25T14:34:16.670 回答
1
[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);
        }
    }
于 2010-08-25T15:28:34.417 回答