【问题标题】:How do I save an image in a SQL Server Database?如何将图像保存在 SQL Server 数据库中?
【发布时间】:2010-08-25 13:58:52
【问题描述】:

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

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

【问题讨论】:

  • 你走了多远。只需将一堆字节插入数据库即可。您能否展示您当前的方法并突出显示您卡住的位置?
  • 这不是重复的,其他问题是一种意见 wiki 讨论。不过,它是相关且有趣的,很好的链接。

标签: c# .net sql-server asp.net-mvc image-uploading


【解决方案1】:

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

Storing Images in DB - Yea or Nay?

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

您可以通过HttpPostedFileBase.InputStream获取二进制数据。

【讨论】:

    【解决方案2】:
    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 类是数据库实体,因此您的数据库中需要NameContentTypeDatauploadedImageHttpPostedFileBase

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:
        [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);
                }
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-10-01
          • 2013-06-26
          • 2015-02-05
          • 2015-08-13
          • 2017-06-28
          • 2015-01-08
          • 2013-02-09
          • 2016-09-28
          相关资源
          最近更新 更多