介紹
在很多情況下,我們需要把圖片保存到數(shù)據(jù)庫中。在某些應(yīng)用程序中,存在一些敏感信息不能被存儲到文件系統(tǒng)中,因為存儲在文件系統(tǒng)上的任何圖片都很容易被用戶非法獲得。
本文將討論在asp.net中怎樣把圖片保存到SQL SERVER數(shù)據(jù)庫中。
在本文中我們將了解到以下幾方面的內(nèi)容:
l 上載圖片文件的要求
l 使用Strem對象
l 獲得上載圖片大小和類型
l 如何使用InputStream方法?
上載圖片文件的要求
在開始上載前我們需要作兩件重要的事情
#Form標(biāo)記的enctype屬性需要被設(shè)置為如下形式:
enctype="mult#提供一個讓用戶選擇圖片文件的Html控件:
<input type=file>
#還要引用System.IO命名空間來處理Strem對象
上述的三項都要應(yīng)用到aspx頁中。在SQL SERVER中還有以下的一些要求:
#一個至少有一個字段類型為Image的表
#另外有一個用來存儲圖片類型的Varchar類型的字段就更好了
那么,我們有了一個有Image字段類型的數(shù)據(jù)表和一個<input type=file>(HTML文件控件)。我們還需要一個提交按鈕,當(dāng)用戶選擇好圖片后可以點擊它。在按鈕的OnClick事件中我們要獲得圖片文件的內(nèi)容并最終把它插入到數(shù)據(jù)表中。讓我們來看看按鈕的OnClick事件,它讀取圖片并把圖片插入到數(shù)據(jù)表中。
提交按鈕的OnClick事件代碼
http://blog.VeVb.com/
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
' Add Parameters to SPROC
Dim prmPersonImage As New SqlParameter("@PersonImage", SqlDbType.Image)
prmPersonImage.Value = ImageContent
myCommand.Parameters.Add(prmPersonImage)
Dim prmPersonImageType As New SqlParameter("@PersonImageType", SqlDbType.VarChar, 255)
prmPersonImageType.Value = strImageType
myCommand.Parameters.Add(prmPersonImageType)
Try
myConnection.Open()
myCommand.ExecuteNonQuery()
myConnection.Close()
Response.Write("New person successfully added!")
Catch SQLexc As SqlException
Response.Write("Insert Failed. Error Details are: " & SQLexc.ToString())
End Try
它是如何工作的?
對象PersonImage 是HTMLInputFile 控件。首先我們要獲得被插入圖片的大小,通過如下方法實現(xiàn):
intImageSize = PersonImage.PostedFile.ContentLength
接著要通過ContenType屬性獲得圖片類型。最后最重要的是要獲得圖片文件流,通過如下方法實現(xiàn):
ImageStream = PersonImage.PostedFile.InputStream
我們有一個byte數(shù)組ImageContent,準(zhǔn)備用來保存圖片內(nèi)容。整個圖片通過Stream對象的Read方法讀取,這個方法有三個參數(shù),即:
#被復(fù)制的圖片內(nèi)容的目標(biāo)位置
#讀的開始位置
#需要被讀的子節(jié)數(shù)
讀聲明如下:
intStatus = ImageStream.Read(ImageContent, 0, intImageSize)
現(xiàn)在,我們讀取了整個圖片內(nèi)容。接著我們需要把圖片內(nèi)容插入SQL數(shù)據(jù)表中,我們將用用一個存儲過程把圖片類型和圖片插入SQL數(shù)據(jù)表。如果你看過上面的代碼清單,你就知道我們把數(shù)據(jù)類型設(shè)置為SqlDbType.Image.就這樣,我們成功地把圖片保存到了SQL SERVER數(shù)據(jù)庫。
新聞熱點
疑難解答