如何在ASP.Net 中把圖片存入數據庫

發表于:2008-10-13來源:作者:點擊數: 標簽:數據庫NetNETASPnet
一、介紹 可能有很多的時候,我們急需把圖片存入到 數據庫 當中。在一些應用程序中,我們可能有一些敏感的資料,由于存儲在文件系統(file system)中的東西,將很容易被某些用戶盜取,所以這些數據不能存放在文件系統中。 在這篇文章中,我們將討論怎樣把圖
一、介紹

  可能有很多的時候,我們急需把圖片存入到數據庫當中。在一些應用程序中,我們可能有一些敏感的資料,由于存儲在文件系統(file system)中的東西,將很容易被某些用戶盜取,所以這些數據不能存放在文件系統中。

  在這篇文章中,我們將討論怎樣把圖片存入到Sql2000當中。

  在這篇文章中我們可以學到以下幾個方面的知識

  1. 插入圖片的必要條件

  2. 使用流對象

  3. 查找準備上傳的圖片的大小和類型

  4.怎么使用InputStream方法?

  在我們開始上傳之前,有兩件重要的事我們需要做:

 ?。ǎ保〧orm 標記的 enctype 屬性應該設置成 enctype="multipart/form-data"

 ?。ǎ玻?需要一個<input type=file>表單來使用戶選擇他們要上傳的文件,同時我們需要導入 System.IO名稱空間來處理流對象。

  把以上三點應用到aspx頁面。同時我們需要對SqlServer做以下的準備。

 ?。ǎ保┬枰辽俸幸粋€圖片類型的字段的表

 ?。ǎ玻┤绻覀冞€有另外一個變字符類型的字段來存儲圖片類型,那樣會更好一些。

  現在,我們準備了一個Sql表(包含了一個image數據類型的字段),還有<input type=file>標記。當然我們還得準備Submit按鈕,以便用戶在選擇了圖片以后提交。在這個按鈕的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

' 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)

原文轉自:http://www.anti-gravitydesign.com

国产97人人超碰caoprom_尤物国产在线一区手机播放_精品国产一区二区三_色天使久久综合给合久久97