在這篇文章中我們可以學到以下幾個方面的知識:
1. 插入圖片的必要條件
2. 使用流對象
3. 查找準備上傳的圖片的大小和類型
4.怎么使用inputstream方法?
插入圖片的必要條件
在我們開始上傳之前,有兩件重要的事我們需要做:
#form 標記的 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)
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控件的對象。首先需要獲得圖片的大小,可以使用下面的代碼實現:
intimagesize = personimage.postedfile.contentlength
然后返回圖片的類型使用contentype屬性。最后,也是最重要的事就是取得image stream,這可以用以下代碼實現:
imagestream = personimage.postedfile.inputstream
我們需要一個字節型數組來存儲image 內容。讀取整個圖片可以使用stream對象的read方法來實現。read(in byte[] buffer,int offset,int count)方法有三個參數。【關于read方法的詳細可以參看.net frameworksdk】他們是:
buffer
字節數組。此方法返回時,該緩沖區包含指定的字符數組,該數組的 offset 和 (offset + count) 之間的值由從當前源中讀取的字節替換。
offset
buffer 中的從零開始的字節偏移量,從此處開始存儲從當前流中讀取的數據。
count
要從當前流中最多讀取的字節數。
這個read方法用以下代碼實現:
intstatus = imagestream.read(imagecontent, 0, intimagesize)
.
現在,我們已經讀取了整個圖片的內容,下一步,我們要把這些內容存入到sql 表。我們將使用存儲過程來完成插入圖片類型和圖片內容到sql 表。如果你瀏覽了上面的代碼,你將會發現我們使用了sqldbtype.image的數據類型(datatype)。ok了,完成了這些,我們也就成功的把圖片存入到sqlserver中了。下面是我們編寫的aspx頁面。
新聞熱點
疑難解答
圖片精選