|
一、把圖片存入數(shù)據(jù)庫中
用到以下幾個方面的知識:
1. 使用流對象
2. 查找準(zhǔn)備上傳的圖片的大小和類型
3.怎么使用InputStream方法
插入圖片的必要條件
1.#Form 標(biāo)記的 enctype 屬性應(yīng)該設(shè)置成 enctype="multipart/form-data"
2.# 需要一個<input type=file>表單來使用戶選擇他們要上傳的文件,同時我們需要導(dǎo)入 System.IO名稱空間來處理流對象
對SqlServer做以下的準(zhǔn)備
1.# 需要至少含有一個圖片類型的字段的表
2.# 如果我們還有另外一個變字符類型的字段來存儲圖片類型,那樣會更好一些。
窗體控件
1.插入圖片用到的是System.Web.UI.HtmlControls.HtmlInputFile控件,我們在webform中放入這個控件,取名為“imgInput”
2.同時再放入一個確認(rèn)上傳按鈕“Button1”
程序代碼
AddImg,用于返回要上傳的圖片內(nèi)容
1Private Function AddImg()Function AddImg(ByVal InputImg As System.Web.UI.HtmlControls.HtmlInputFile, ByVal ImgType As String, ByVal MaxSize As Int64) As Byte()
2'傳入一個htmlinputfile控件,一個上傳圖片格式和一個上傳圖片最大值,返回圖片的內(nèi)容,既要寫入數(shù)據(jù)庫中的內(nèi)容,你也可以同時寫入圖片類型
3 Dim intImageSize As Int64
4 Dim strImageType As String
5 Dim ImageStream As Stream
6 ' Gets the Image Type
7 strImageType=InputImg.PostedFile.ContentType
8 If strImageType <> ImgType Then
9 Response.Write("<script>alert('圖片類型為""')</script>") 'jgp類型為"image/pjpeg"
10 Exit Function
11 End If
12 ' Gets the Size of the Image
13 intImageSize = InputImg.PostedFile.ContentLength
14 If intImageSize > MaxSize Then
15 Response.Write("<script>alert('圖片不得大于K')</script>")
16 Exit Function
17 End If
18 ' Reads the Image
19 ImageStream = InputImg.PostedFile.InputStream
20 Dim ImageContent(intImageSize) As Byte
21 Dim intStatus As Integer
22 intStatus = ImageStream.Read(ImageContent, 0, intImageSize)
23 Return ImageContent
24 End Function
示例調(diào)用
Dim imageContent() As Byte
imageContent = AddImg(fileImg, "image/pjpeg", 512000)'上傳圖片類型為jpg,最大不超過500K
插入數(shù)據(jù)庫
我想這部分就不用寫了吧,你可以用任何方式(推薦使用存儲過程),將imageContent插入到數(shù)據(jù)庫中類型為image的字段就行了。
二、把圖片從數(shù)據(jù)庫中讀出
這部分比較簡單:
假設(shè)img變量是你從數(shù)據(jù)庫中取出的圖片內(nèi)容
那么直接使用
Response.BinaryWrite(img)
就可以將圖片輸出到頁面上了
三:總結(jié)
將圖片存放在數(shù)據(jù)庫中其實是起到了圖片保護的作用,這樣就算別人瀏覽你的機器也看不到你的圖片,也可以用來保護重要的圖片資料。
AspNet技術(shù):在ASP.net中保存/取出圖片入/從SQL數(shù)據(jù)庫,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。