一聚教程网:一个值得你收藏的教程网站

热门教程

在ASP.NET中把图片保存到SQL SERVER数据库

时间:2022-06-30 10:27:28 编辑:袖梨 来源:一聚教程网

介绍
在很多情况下,我们需要把图片保存到数据库中。在某些应用程序中,存在一些敏感信息不能被存储到文件系统中,因为存储在文件系统上的任何图片都很容易被用户非法获得。
本文将讨论在ASP.NET中怎样把图片保存到SQL SERVER数据库中。
在本文中我们将了解到以下几方面的内容:
l???????? 上载图片文件的要求
l???????? 使用Strem对象
l???????? 获得上载图片大小和类型
l???????? 如何使用InputStream方法?
上载图片文件的要求
在开始上载前我们需要作两件重要的事情
#Form标记的enctype属性需要被设置为如下形式:
enctype="multipart/form-data"
#提供一个让用户选择图片文件的Html控件:

#还要引用System.IO命名空间来处理Strem对象
上述的三项都要应用到aspx页中。在SQL SERVER中还有以下的一些要求:
#一个至少有一个字段类型为Image的表
#另外有一个用来存储图片类型的Varchar类型的字段就更好了
那么,我们有了一个有Image字段类型的数据表和一个(HTML文件控件)。我们还需要一个提交按钮,当用户选择好图片后可以点击它。在按钮的OnClick事件中我们要获得图片文件的内容并最终把它插入到数据表中。让我们来看看按钮的OnClick事件,它读取图片并把图片插入到数据表中。
提交按钮的OnClick事件代码
?
??Dim intImageSize As Int64
????Dim strImageType As String
????Dim ImageStream As Stream
????' Gets the Size of the Image
????intImageSize = PersonImage.PostedFile.ContentLength
????' Gets the Image Type
????strImageType = PersonImage.PostedFile.ContentType
????' Reads the Image
????ImageStream = PersonImage.PostedFile.InputStream
????Dim ImageContent(intImageSize) As Byte
????Dim intStatus As Integer
????intStatus = ImageStream.Read(ImageContent, 0, intImageSize)
????' Create Instance of Connection and Command Object
????Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
????Dim myCommand As New SqlCommand("sp_person_isp", myConnection)
????' Mark the Command as a SPROC
????myCommand.CommandType = CommandType.StoredProcedure

热门栏目